@extends('layouts.app')

@section('title', isset($patient) ? __('clinicCore::lang.edit') : __('clinicCore::lang.add_pet'))

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

@section('content')
<section class="content-header">
    <h1><i class="fas fa-notes-medical"></i>
        {{ isset($patient) ? __('clinicCore::lang.edit') . ' — ' . $patient->patient_name : __('clinicCore::lang.add_pet') }}
    </h1>
</section>

<section class="content">
    <form method="POST" action="{{ isset($patient) ? route('clinic.patients.update', $patient->id) : route('clinic.patients.store') }}"
          enctype="multipart/form-data">
        @csrf
        <div class="row">
            <div class="col-md-8">
                @component('components.widget', ['class' => 'box-primary', 'title' => __('clinicCore::lang.pet') . ' ' . __('clinicCore::lang.description')])
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.pet_owner') <span class="text-danger">*</span></label>
                                <select name="contact_id" id="contact_id" class="form-control" style="width:100%" required
                                    {{ isset($preselectedContact) ? 'disabled' : '' }}>
                                    @if(isset($patient) && $patient->owner)
                                        <option value="{{ $patient->contact_id }}" selected>{{ $patient->owner->name }}</option>
                                    @elseif(isset($preselectedContact))
                                        <option value="{{ $preselectedContact->id }}" selected>
                                            {{ $preselectedContact->name }}{{ $preselectedContact->mobile ? ' (' . $preselectedContact->mobile . ')' : '' }}
                                        </option>
                                    @endif
                                </select>
                                @if(isset($preselectedContact))
                                    <input type="hidden" name="contact_id" value="{{ $preselectedContact->id }}">
                                    <small class="text-muted">{{ $preselectedContact->name }} — <a href="{{ route('clinic.patient-contacts.show', optional(\Modules\ClinicCore\Entities\ClcPatientContactDetail::where('contact_id', $preselectedContact->id)->first())->id ?? 0) }}">@lang('clinicCore::lang.pet_owner')</a></small>
                                @endif
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.patient_name') <span class="text-danger">*</span></label>
                                <input type="text" name="patient_name" class="form-control"
                                    value="{{ old('patient_name', isset($patient) ? $patient->patient_name : '') }}" required>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.default_specialty')</label>
                                @php $curSpec = old('default_specialty_id', isset($patient) ? $patient->default_specialty_id : ''); @endphp
                                <select name="default_specialty_id" id="default_specialty_id" class="form-control">
                                    <option value="">—</option>
                                    @foreach(($specialties ?? collect()) as $spec)
                                        <option value="{{ $spec->id }}" data-code="{{ $spec->code }}" {{ (string)$curSpec === (string)$spec->id ? 'selected' : '' }}>{{ $spec->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.serial_no')</label>
                                <input type="text" name="serial_no" class="form-control"
                                    value="{{ old('serial_no', isset($patient) ? $patient->serial_no : '') }}">
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-3">
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.gender')</label>
                                <select name="gender" class="form-control">
                                    <option value="unknown" {{ old('gender', isset($patient) ? $patient->gender : '') == 'unknown' ? 'selected' : '' }}>@lang('clinicCore::lang.unknown')</option>
                                    <option value="male" {{ old('gender', isset($patient) ? $patient->gender : '') == 'male' ? 'selected' : '' }}>@lang('clinicCore::lang.male')</option>
                                    <option value="female" {{ old('gender', isset($patient) ? $patient->gender : '') == 'female' ? 'selected' : '' }}>@lang('clinicCore::lang.female')</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.dob')</label>
                                <input type="text" id="dob_display" class="form-control" autocomplete="off" placeholder="Date of Birth">
                                <input type="hidden" name="dob" id="dob_iso" value="{{ old('dob', isset($patient) && $patient->dob ? $patient->dob->format('Y-m-d') : '') }}">
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.bloodgroup')</label>
                                <input type="text" name="bloodgroup" class="form-control"
                                    value="{{ old('bloodgroup', isset($patient) ? $patient->bloodgroup : '') }}">
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.height_cm')</label>
                                <input type="number" step="0.1" name="height_cm" class="form-control" placeholder="cm"
                                    value="{{ old('height_cm', isset($patient) ? $patient->height_cm : '') }}">
                            </div>
                        </div>
                    </div>

                    {{-- ── P3-T1 Identity (patient master extensions) ────────────── --}}
                    <hr style="margin:6px 0 14px;border-top:1px dashed #e2e8f0;">
                    <h5 style="font-weight:700;text-transform:uppercase;letter-spacing:.5px;color:#64748b;font-size:12px;margin:0 0 10px;">
                        <i class="fa fa-id-card text-primary"></i> @lang('clinicCore::lang.identity')
                    </h5>
                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.preferred_name')</label>
                                <input type="text" name="preferred_name" class="form-control"
                                    value="{{ old('preferred_name', isset($patient) ? $patient->preferred_name : '') }}">
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.national_id')</label>
                                <input type="text" name="national_id" class="form-control"
                                    value="{{ old('national_id', isset($patient) ? $patient->national_id : '') }}">
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.passport_number')</label>
                                <input type="text" name="passport_number" class="form-control"
                                    value="{{ old('passport_number', isset($patient) ? $patient->passport_number : '') }}">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-3">
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.marital_status')</label>
                                @php $curMarital = old('marital_status', isset($patient) ? $patient->marital_status : ''); @endphp
                                <select name="marital_status" class="form-control">
                                    <option value="">—</option>
                                    @foreach(['single','married','divorced','widowed'] as $ms)
                                        <option value="{{ $ms }}" {{ $curMarital === $ms ? 'selected' : '' }}>@lang('clinicCore::lang.marital_' . $ms)</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.nationality')</label>
                                <input type="text" name="nationality" class="form-control"
                                    value="{{ old('nationality', isset($patient) ? $patient->nationality : '') }}">
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.primary_language')</label>
                                <input type="text" name="primary_language" class="form-control"
                                    value="{{ old('primary_language', isset($patient) ? $patient->primary_language : '') }}">
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.gender_identity')</label>
                                <input type="text" name="gender_identity" class="form-control"
                                    value="{{ old('gender_identity', isset($patient) ? $patient->gender_identity : '') }}">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.registered_location')</label>
                                @php $curLoc = old('registered_location_id', isset($patient) ? $patient->registered_location_id : ''); @endphp
                                <select name="registered_location_id" class="form-control">
                                    <option value="">—</option>
                                    @foreach(($locations ?? collect()) as $loc)
                                        <option value="{{ $loc->id }}" {{ (string)$curLoc === (string)$loc->id ? 'selected' : '' }}>{{ $loc->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                    </div>
                    <hr style="margin:6px 0 14px;border-top:1px dashed #e2e8f0;">

                    <div class="row">
                        <div class="col-md-12">
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.allergies')</label>
                                <textarea name="allergies" class="form-control" rows="2" placeholder="Known drug / contact allergies">{{ old('allergies', isset($patient) ? $patient->allergies : '') }}</textarea>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.chronic_conditions')</label>
                                <textarea name="chronic_conditions" class="form-control" rows="2" placeholder="Diabetes, autoimmune, etc.">{{ old('chronic_conditions', isset($patient) ? $patient->chronic_conditions : '') }}</textarea>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.family_history')</label>
                                <textarea name="family_history" class="form-control" rows="2" placeholder="Hereditary / family medical history">{{ old('family_history', isset($patient) ? $patient->family_history : '') }}</textarea>
                            </div>
                        </div>
                    </div>

                    {{-- Specialty-specific patient fields, contributed by structural specialty plugins
                         (e.g. Dermatology skin profile). Each fragment is shown only when its specialty
                         is the patient's selected default specialty. --}}
                    @php $clcSpecDrivers = \Modules\ClinicCore\Entities\Services\SpecialtyDriverRegistry::all(); @endphp
                    @foreach($clcSpecDrivers as $clcDriverKey => $clcDriver)
                        @php $clcFrag = $clcDriver->patientFormFragment(); @endphp
                        @if($clcFrag)
                            @php
                                $clcSpecId = optional(($specialties ?? collect())->firstWhere('code', $clcDriverKey))->id;
                                $clcShow = (string) old('default_specialty_id', isset($patient) ? $patient->default_specialty_id : '') === (string) $clcSpecId;
                            @endphp
                            <div class="clc-specialty-fields" data-specialty-id="{{ $clcSpecId }}" style="{{ $clcShow ? '' : 'display:none;' }}">
                                @includeIf($clcFrag, ['patient' => $patient ?? null])
                            </div>
                        @endif
                    @endforeach

                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.status')</label>
                                <select name="status" class="form-control">
                                    <option value="active" {{ old('status', isset($patient) ? $patient->status : 'active') == 'active' ? 'selected' : '' }}>@lang('clinicCore::lang.active')</option>
                                    <option value="inactive" {{ old('status', isset($patient) ? $patient->status : '') == 'inactive' ? 'selected' : '' }}>@lang('clinicCore::lang.inactive')</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-8">
                            <div class="form-group">
                                <label><i class="fa fa-user-md text-primary"></i> @lang('clinicCore::lang.preferred_doctor')
                                    <small class="text-muted">(@lang('clinicCore::lang.pet_level_override'))</small>
                                </label>
                                <select name="preferred_doctor_id" id="preferred_doctor_id" class="form-control" style="width:100%">
                                    <option value="">— @lang('clinicCore::lang.use_owner_preferred_doctor') —</option>
                                    @foreach(($doctors ?? []) as $doc)
                                        <option value="{{ $doc->id }}"
                                            {{ (string) old('preferred_doctor_id', isset($patient) ? $patient->preferred_doctor_id : '') === (string) $doc->id ? 'selected' : '' }}>
                                            {{ $doc->name }}{{ $doc->specialization ? ' — ' . $doc->specialization : '' }}
                                        </option>
                                    @endforeach
                                </select>
                                <small class="text-muted">@lang('clinicCore::lang.pet_preferred_doctor_hint')</small>
                            </div>
                        </div>
                    </div>
                @endcomponent
            </div>

            <div class="col-md-4">
                @component('components.widget', ['class' => 'box-default', 'title' => __('clinicCore::lang.photo')])
                    <div class="form-group">
                        <input type="file" name="photo" accept="image/*">
                    </div>
                @endcomponent

                <div class="form-group">
                    <button type="submit" class="btn btn-primary btn-block">
                        <i class="fa fa-save"></i>
                        {{ isset($patient) ? __('clinicCore::lang.update') : __('clinicCore::lang.save') }}
                    </button>
                    <a href="{{ route('clinic.patients.index') }}" class="btn btn-default btn-block">@lang('clinicCore::lang.cancel')</a>
                </div>
            </div>
        </div>
    </form>
</section>
@endsection

@section('javascript')
<script>
$(document).ready(function() {
    // Show only the specialty-specific field block matching the chosen default specialty.
    function clcToggleSpecialtyFields() {
        var id = String($('#default_specialty_id').val() || '');
        $('.clc-specialty-fields').each(function () {
            var match = String($(this).data('specialty-id')) === id && id !== '';
            $(this).toggle(match);
            // Only the active specialty's inputs may submit — disable the hidden
            // blocks so shared field names (bmi, notes, planned_procedure, …)
            // across specialties don't collide on POST.
            $(this).find('input, select, textarea').prop('disabled', !match);
        });
    }
    $('#default_specialty_id').on('change', clcToggleSpecialtyFields);
    clcToggleSpecialtyFields();

    $('#dob_display').datepicker({
        todayHighlight: true,
        autoclose: true,
        format: datepicker_date_format,
        endDate: new Date()
    }).on('changeDate', function(e) {
        if (e.dates.length) {
            var d = e.dates[0];
            var iso = d.getFullYear() + '-' +
                      String(d.getMonth() + 1).padStart(2, '0') + '-' +
                      String(d.getDate()).padStart(2, '0');
            $('#dob_iso').val(iso);
        }
    }).on('clearDate', function() {
        $('#dob_iso').val('');
    });

    var dobIso = $('#dob_iso').val();
    if (dobIso) {
        var parts = dobIso.split('-');
        $('#dob_display').datepicker('setDate',
            new Date(+parts[0], +parts[1] - 1, +parts[2])
        );
    }

    $('#preferred_doctor_id').select2({
        width: '100%',
        placeholder: '— Use contact\'s preferred doctor —',
        allowClear: true
    });

    @if(!isset($preselectedContact))
    $('#contact_id').select2({
        width: '100%',
        minimumInputLength: 1,
        minimumResultsForSearch: -1,
        ajax: {
            url: '{{ route('clinic.patient-contacts.search') }}',
            dataType: 'json',
            delay: 300,
            data: function (params) { return { q: params.term }; },
            processResults: function (data) { return { results: data }; }
        },
        placeholder: '{{ __("clinicCore::lang.search") }} owner...',
        language: {
            inputTooShort: function() { return 'Type to search...'; },
            noResults: function() { return 'No contacts found'; },
            searching: function() { return 'Searching...'; }
        }
    });
    @endif
});
</script>
@endsection
