@extends('layouts.app')

@section('title', 'Birth & Death Records')

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

@section('content')
<section class="content-header">
    <h1><i class="fas fa-book-medical"></i> Birth & Death Records</h1>
</section>

<section class="content">
    <div class="row" style="margin-bottom:10px;">
        <div class="col-md-12">
            <div class="btn-group" style="margin-right:8px;">
                <button class="btn btn-default btn-sm filter-bdr active" data-type="">All</button>
                <button class="btn btn-success btn-sm filter-bdr" data-type="birth">
                    <i class="fa fa-heart"></i> Births
                </button>
                <button class="btn btn-danger btn-sm filter-bdr" data-type="death">
                    <i class="fa fa-cross"></i> Deaths
                </button>
            </div>
            @can('vet_clinic.manage_pets')
            <button class="btn btn-primary pull-right" data-toggle="modal" data-target="#bdrModal">
                <i class="fa fa-plus"></i> Record Event
            </button>
            @endcan
        </div>
    </div>

    <div class="row">
        <div class="col-md-12">
            @component('components.widget', ['class' => 'box-primary'])
                <table class="table table-bordered table-striped" id="bdr_table">
                    <thead>
                        <tr>
                            <th>Type</th>
                            <th>Pet</th>
                            <th>Owner</th>
                            <th>Doctor</th>
                            <th>Event Date</th>
                            <th>Weight (kg)</th>
                            <th>Notes</th>
                            <th>@lang('vetClinic::lang.actions')</th>
                        </tr>
                    </thead>
                </table>
            @endcomponent
        </div>
    </div>
</section>

{{-- Add/Edit Modal --}}
<div class="modal fade" id="bdrModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" style="font-size:15px;">&times;</button>
                <h4 class="modal-title" id="bdr_modal_title">Record Birth / Death</h4>
            </div>
            <div class="modal-body">
                <input type="hidden" id="bdr_id">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Record Type <span class="text-danger">*</span></label>
                            <select id="bdr_record_type" class="form-control" required>
                                <option value="birth">Birth</option>
                                <option value="death">Death</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Doctor</label>
                            <select id="bdr_doctor_id" class="form-control select2-bdr" style="width:100%">
                                <option value="">— None —</option>
                                @foreach($doctors as $doc)
                                <option value="{{ $doc->id }}">{{ $doc->name }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>@lang('vetClinic::lang.pet_owner') <span class="text-danger">*</span></label>
                            <select id="bdr_contact_id" class="form-control select2-owner-bdr" style="width:100%" required>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Pet <span class="text-danger">*</span></label>
                            <select id="bdr_pet_id" class="form-control select2-bdr" style="width:100%" required>
                                <option value="">— Select Owner First —</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Event Date <span class="text-danger">*</span></label>
                            <input type="date" id="bdr_event_date" class="form-control" value="{{ date('Y-m-d') }}" required>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Event Time</label>
                            <input type="time" id="bdr_event_time" class="form-control">
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label>Weight at Time (kg)</label>
                    <input type="number" id="bdr_weight_kg" class="form-control" step="0.01" min="0">
                </div>
                <div class="form-group">
                    <label>Notes</label>
                    <textarea id="bdr_notes" class="form-control" rows="2"></textarea>
                </div>
                <div id="bdr_death_warning" style="display:none;" class="alert alert-warning">
                    <i class="fa fa-exclamation-triangle"></i> Recording a <strong>Death</strong> will mark the pet as deceased on their profile.
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-default" data-dismiss="modal">@lang('vetClinic::lang.cancel')</button>
                <button class="btn btn-primary" id="btn_save_bdr">@lang('vetClinic::lang.save')</button>
            </div>
        </div>
    </div>
</div>
@endsection

@section('javascript')
<script>
var currentType = '';
var bdrTable = $('#bdr_table').DataTable({
    processing: true,
    serverSide: true,
    order: [[4, 'desc']],
    ajax: {
        url: '{{ route('vc.birth-death.list') }}',
        data: function (d) { d.record_type = currentType; }
    },
    columns: [
        { data: 'type_badge', name: 'record_type', orderable: false },
        { data: 'pet_name', name: 'pet_name', orderable: false },
        { data: 'owner_name', name: 'owner_name', orderable: false },
        { data: 'doctor_name', name: 'doctor_name', orderable: false },
        { data: 'event_date', name: 'event_date' },
        { data: 'weight_kg', name: 'weight_kg' },
        { data: 'notes', name: 'notes', orderable: false },
        { data: 'action', name: 'action', orderable: false, searchable: false }
    ]
});

$('.filter-bdr').on('click', function () {
    $('.filter-bdr').removeClass('active');
    $(this).addClass('active');
    currentType = $(this).data('type');
    bdrTable.ajax.reload();
});

// Show/hide death warning
$('#bdr_record_type').on('change', function () {
    $('#bdr_death_warning').toggle($(this).val() === 'death');
});

// Open modal reset
$('[data-target="#bdrModal"]').on('click', function () {
    $('#bdr_modal_title').text('Record Birth / Death');
    $('#bdr_id').val('');
    $('#bdr_record_type').val('birth').trigger('change');
    $('#bdr_contact_id, #bdr_pet_id').val(null).trigger('change');
    $('#bdr_doctor_id').val('');
    $('#bdr_event_date').val('{{ date('Y-m-d') }}');
    $('#bdr_event_time,#bdr_notes').val('');
    $('#bdr_weight_kg').val('');
});

$('.select2-bdr').select2({ width: '100%', dropdownParent: $('#bdrModal') });

$('#bdr_contact_id').select2({
    width: '100%', minimumInputLength: 2,
    dropdownParent: $('#bdrModal'),
    ajax: {
        url: '{{ route('vc.pet-owners.search') }}',
        dataType: 'json', delay: 300,
        data: function (p) { return { q: p.term }; },
        processResults: function (d) { return { results: d }; }
    },
    placeholder: 'Search owner...'
}).on('select2:select', function (e) {
    var contactId = e.params.data.id;
    $.get('{{ url('vet-clinic/pets/by-owner') }}/' + contactId, function (data) {
        $('#bdr_pet_id').empty().append('<option value="">— Select Pet —</option>');
        $.each(data, function (i, pet) {
            $('#bdr_pet_id').append('<option value="' + pet.id + '">' + pet.text + '</option>');
        });
    });
});

// Edit
$(document).on('click', '.btn-edit-bdr', function () {
    var id = $(this).data('id');
    $.get('{{ url('vet-clinic/birth-death') }}/' + id + '/edit', function (d) {
        $('#bdr_modal_title').text('Edit Record');
        $('#bdr_id').val(d.id);
        $('#bdr_record_type').val(d.record_type).trigger('change');
        $('#bdr_event_date').val(d.event_date ? d.event_date.substring(0,10) : '');
        $('#bdr_event_time').val(d.event_time);
        $('#bdr_weight_kg').val(d.weight_kg);
        $('#bdr_notes').val(d.notes);
        $('#bdr_doctor_id').val(d.doctor_id);
        $('#bdrModal').modal('show');
    });
});

$('#btn_save_bdr').on('click', function () {
    var id = $('#bdr_id').val();
    var url = id ? '{{ url('vet-clinic/birth-death') }}/' + id + '/update' : '{{ route('vc.birth-death.store') }}';
    $.ajax({
        url: url, method: 'POST',
        data: {
            _token: '{{ csrf_token() }}',
            record_type: $('#bdr_record_type').val(),
            pet_id: $('#bdr_pet_id').val(),
            contact_id: $('#bdr_contact_id').val(),
            doctor_id: $('#bdr_doctor_id').val(),
            event_date: $('#bdr_event_date').val(),
            event_time: $('#bdr_event_time').val(),
            weight_kg: $('#bdr_weight_kg').val(),
            notes: $('#bdr_notes').val()
        },
        success: function (res) {
            if (res.success) { $('#bdrModal').modal('hide'); toastr.success(res.msg); bdrTable.ajax.reload(); }
        },
        error: function (xhr) { toastr.error(xhr.responseJSON?.message ?? 'Error'); }
    });
});

$(document).on('click', '.btn-delete-bdr', function () {
    if (!confirm('@lang('vetClinic::lang.confirm_delete')')) return;
    $.ajax({
        url: '{{ url('vet-clinic/birth-death') }}/' + $(this).data('id'),
        method: 'DELETE',
        data: { _token: '{{ csrf_token() }}' },
        success: function (res) { if (res.success) { toastr.success(res.msg); bdrTable.ajax.reload(); } }
    });
});
</script>
@endsection
