@extends('layouts.app')

@section('content')
<style>
    .profit-badge {
        font-size: 13px;
        padding: 6px 10px;
        border-radius: 6px;
        display: inline-block;
        min-width: 90px;
    }

    .error-text {
        color: #ff3e1d;
        font-size: 13px;
        margin-top: 5px;
    }

    .animal-table-image {
        width: 70px;
        height: 70px;
        object-fit: cover;
        border-radius: 8px;
    }

    .animal-preview-image {
        width: 80px;
        height: 80px;
        object-fit: cover;
        border-radius: 8px;
        border: 1px solid #ddd;
    }

    .animal-image-box {
        position: relative;
        display: inline-block;
        margin: 5px;
    }

    .animal-image-delete {
        position: absolute;
        top: -7px;
        right: -7px;
        border-radius: 50%;
        width: 24px;
        height: 24px;
        line-height: 20px;
        padding: 0;
    }
</style>

<div class="container-xxl flex-grow-1 container-p-y">
    <div class="card">

        <div class="card-header">
            <div class="datatable-header-top">
                <div class="datatable-header-title">
                    <h5 class="mb-0">Animals</h5>
                </div>

                <div class="datatable-toolbar-target">
                    <div class="datatable-length-slot"></div>
                    <div class="datatable-manager-slot">
                        @include('partials.manager-filter', ['filterId' => 'animals-manager-filter'])
                    </div>
                    <div class="datatable-search-slot"></div>
                </div>

                <div class="datatable-header-action text-end">
                    @can('create animals')
                        <button type="button" class="btn btn-primary" id="addAnimalBtn">
                            Add Animal
                        </button>
                    @endcan
                </div>
            </div>
            <hr>
        </div>

        <div class="card-body">

            <div id="ajaxMessage"></div>
            <div class="table-responsive">
                <table id="bookings-table" class="table table-bordered align-middle text-center">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Image</th>
                            <th style="min-width: 102px;">Name</th>
                            <th>Cattle Name</th>
                            <th>Per Animal Expense</th>
                            <th>Buy Price</th>
                            <th>Total Expense</th>
                            <th>Sale Price</th>
                            <th>Faida / Profit</th>
                            <th>Tag Number</th>
                            <th width="220">Action</th>
                        </tr>
                    </thead>

                    <tbody>
                        @foreach($animals as $animal)
                            @php
                                $lastImage = $animal->images->last();
                                $profitLoss = $animal->profit_loss;

                                if (!is_null($profitLoss)) {
                                    if ($profitLoss > 0) {
                                        $profitText = '+' . number_format($profitLoss, 2);
                                        $profitClass = 'bg-success';
                                    } elseif ($profitLoss < 0) {
                                        $profitText = number_format($profitLoss, 2);
                                        $profitClass = 'bg-danger';
                                    } else {
                                        $profitText = number_format($profitLoss, 2);
                                        $profitClass = 'bg-secondary';
                                    }
                                }
                            @endphp

                            <tr id="animal-row-{{ $animal->id }}">
                                <td>{{ $loop->iteration }}</td>

                                <td>
                                    @if($lastImage)
                                        <img src="{{ asset($lastImage->image) }}" class="animal-table-image">
                                    @else
                                        N/A
                                    @endif
                                </td>

                                <td>{{ $animal->animal_name }}</td>
                                <td>{{ $animal->category->title ?? 'N/A' }}</td>
                                <td>{{ number_format($animal->expense_per_animal ?? 0, 2) }}</td>
                                <td>{{ number_format($animal->buy_price ?? 0, 2) }}</td>
                                <td>{{ number_format($animal->total_expense ?? 0, 2) }}</td>

                                <td>
                                    @if(!is_null($animal->sale_price) && $animal->sale_price !== '')
                                        {{ number_format($animal->sale_price, 2) }}
                                    @else
                                        N/A
                                    @endif
                                </td>

                                <td>
                                    @if(is_null($profitLoss))
                                        N/A
                                    @else
                                        <span class="badge {{ $profitClass }} profit-badge">
                                            {{ $profitText }}
                                        </span>
                                    @endif
                                </td>

                                <td>{{ $animal->tag_number ?? 'N/A' }}</td>

                                <td>
                                    <div class="d-inline-flex align-items-center action-icons">

                                        @can('view animals')
                                            <button type="button"
                                                    class="action-icon text-info border-0 bg-transparent p-0 viewAnimalBtn"
                                                    data-id="{{ $animal->id }}"
                                                    title="View">
                                                <i class="bx bx-show"></i>
                                            </button>
                                        @endcan

                                        @can('update animals')
                                            <button type="button"
                                                    class="action-icon text-warning border-0 bg-transparent p-0 editAnimalBtn"
                                                    data-id="{{ $animal->id }}"
                                                    title="Edit">
                                                <i class="bx bx-edit-alt"></i>
                                            </button>
                                        @endcan

                                        @can('delete animals')
                                            <button type="button"
                                                    class="action-icon text-danger border-0 bg-transparent p-0 deleteAnimalBtn"
                                                    data-id="{{ $animal->id }}"
                                                    title="Delete">
                                                <i class="bx bx-trash"></i>
                                            </button>
                                        @endcan

                                    </div>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>

                </table>
            </div>
        </div>
    </div>
</div>

{{-- Add / Edit Modal --}}
<div class="modal fade" id="animalFormModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <form id="animalForm" enctype="multipart/form-data">
            @csrf

            <input type="hidden" id="animal_id" name="animal_id">
            <input type="hidden" id="form_method" name="_method" value="POST">

            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="animalModalTitle">Add Animal</h5>

                    <button type="button"
                            class="btn-close"
                            data-bs-dismiss="modal"
                            aria-label="Close"></button>
                </div>

                <div class="modal-body">

                    <div id="formErrors"></div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">
                                Cattle Category <span class="text-danger">*</span>
                            </label>

                            <select name="cattle_category_id" id="cattle_category_id" class="form-control">
                                <option value="">Select Category</option>
                                @foreach($categories as $category)
                                    <option value="{{ $category->id }}">
                                        {{ $category->title }}
                                    </option>
                                @endforeach
                            </select>

                            <div class="error-text" id="cattleCategoryError"></div>
                        </div>

                        <div class="col-md-6 mb-3">
                            <label class="form-label">
                                Animal Name <span class="text-danger">*</span>
                            </label>

                            <input type="text"
                                   name="animal_name"
                                   id="animal_name"
                                   class="form-control"
                                   placeholder="Enter animal name">

                            <div class="error-text" id="animalNameError"></div>
                        </div>

                        <div class="col-md-6 mb-3">
                            <label class="form-label">Buy Date</label>

                            <input type="date"
                                   name="buy_date"
                                   id="buy_date"
                                   class="form-control">

                            <div class="error-text" id="buyDateError"></div>
                        </div>

                        <div class="col-md-6 mb-3">
                            <label class="form-label">Buy Price</label>

                            <input type="number"
                                   step="0.01"
                                   min="0"
                                   name="buy_price"
                                   id="buy_price"
                                   class="form-control"
                                   placeholder="Enter buy price">

                            <div class="error-text" id="buyPriceError"></div>
                        </div>

                        <div class="col-md-6 mb-3">
                            <label class="form-label">Sale Date</label>

                            <input type="date"
                                   name="sale_date"
                                   id="sale_date"
                                   class="form-control">

                            <div class="error-text" id="saleDateError"></div>
                        </div>

                        <div class="col-md-6 mb-3">
                            <label class="form-label">Sale Price</label>

                            <input type="number"
                                   step="0.01"
                                   min="0"
                                   name="sale_price"
                                   id="sale_price"
                                   class="form-control"
                                   placeholder="Enter sale price">

                            <div class="error-text" id="salePriceError"></div>
                        </div>

                        <div class="col-md-6 mb-3">
                            <label class="form-label">Breed</label>

                            <input type="text"
                                   name="breed"
                                   id="breed"
                                   class="form-control"
                                   placeholder="Enter breed">

                            <div class="error-text" id="breedError"></div>
                        </div>

                        <div class="col-md-6 mb-3">
                            <label class="form-label">Weight</label>

                            <input type="number"
                                   step="0.01"
                                   min="0"
                                   name="weight"
                                   id="weight"
                                   class="form-control"
                                   placeholder="Enter weight">

                            <div class="error-text" id="weightError"></div>
                        </div>

                        <div class="col-md-6 mb-3">
                            <label class="form-label">Tag Number</label>

                            <input type="text"
                                   name="tag_number"
                                   id="tag_number"
                                   class="form-control"
                                   placeholder="Enter tag number">

                            <div class="error-text" id="tagNumberError"></div>
                        </div>

                        <div class="col-md-6 mb-3">
                            <label class="form-label">Images</label>

                            <input type="file"
                                   name="images[]"
                                   id="images"
                                   class="form-control"
                                   multiple
                                   accept="image/*">

                            <div class="error-text" id="imagesError"></div>
                        </div>

                        <div class="col-md-12 mb-3">
                            <label class="form-label">Existing Images</label>
                            <div id="existingImages" class="border rounded p-2">
                                No images found.
                            </div>
                        </div>

                        <div class="col-md-12 mb-3">
                            <label class="form-label">Notes</label>

                            <textarea name="notes"
                                      id="notes"
                                      rows="3"
                                      class="form-control"
                                      placeholder="Enter notes"></textarea>

                            <div class="error-text" id="notesError"></div>
                        </div>
                    </div>

                </div>

                <div class="modal-footer">
                    <button type="button"
                            class="btn btn-label-secondary"
                            data-bs-dismiss="modal">
                        Cancel
                    </button>

                    <button type="submit" class="btn btn-primary" id="saveAnimalBtn">
                        Save
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

{{-- View Modal --}}
<div class="modal fade" id="animalViewModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">

            <div class="modal-header">
                <h5 class="modal-title">View Animal</h5>

                <button type="button"
                        class="btn-close"
                        data-bs-dismiss="modal"
                        aria-label="Close"></button>
            </div>

            <div class="modal-body">
                <table class="table table-bordered">
                    <tr>
                        <th width="25%">Animal Name</th>
                        <td id="viewAnimalName"></td>
                    </tr>

                    <tr>
                        <th>Category</th>
                        <td id="viewCategory"></td>
                    </tr>

                    <tr>
                        <th>Buy Date</th>
                        <td id="viewBuyDate"></td>
                    </tr>

                    <tr>
                        <th>Buy Price</th>
                        <td id="viewBuyPrice"></td>
                    </tr>

                    <tr>
                        <th>Per Animal Expense</th>
                        <td id="viewPerAnimalExpense"></td>
                    </tr>

                    <tr>
                        <th>Total Expense</th>
                        <td id="viewTotalExpense"></td>
                    </tr>

                    <tr>
                        <th>Sale Date</th>
                        <td id="viewSaleDate"></td>
                    </tr>

                    <tr>
                        <th>Sale Price</th>
                        <td id="viewSalePrice"></td>
                    </tr>

                    <tr>
                        <th>Profit / Loss</th>
                        <td id="viewProfitLoss"></td>
                    </tr>

                    <tr>
                        <th>Breed</th>
                        <td id="viewBreed"></td>
                    </tr>

                    <tr>
                        <th>Weight</th>
                        <td id="viewWeight"></td>
                    </tr>

                    <tr>
                        <th>Tag Number</th>
                        <td id="viewTagNumber"></td>
                    </tr>

                    <tr>
                        <th>Notes</th>
                        <td id="viewNotes"></td>
                    </tr>

                    <tr>
                        <th>Images</th>
                        <td id="viewImages"></td>
                    </tr>
                </table>
            </div>

            <div class="modal-footer">
                <button type="button"
                        class="btn btn-label-secondary"
                        data-bs-dismiss="modal">
                    Close
                </button>
            </div>

        </div>
    </div>
</div>

@endsection

@push('script')
<script>
$(document).ready(function () {
    function normalizeToolbarControl($control, type) {
        if (!$control.length || $control.data('toolbar-normalized')) {
            return;
        }

        let $label = $control.find('label').first();

        if (type === 'length') {
            let $select = $control.find('select').first();

            if ($label.length && $select.length) {
                $select.detach();
                $label.empty().append($select);
            }
        } else {
            let $input = $control.find('input').first();

            if ($input.length) {
                $input.attr('placeholder', 'Search');
            }

            if ($label.length && $input.length) {
                $input.detach();
                $label.empty().append($input);
            }
        }

        $control.data('toolbar-normalized', true);
    }

    function moveTableControlsToHeader(tableApi) {
        let $wrapper = $(tableApi.table().container());
        let $card = $wrapper.closest('.card');
        let $toolbarTarget = $card.find('.datatable-toolbar-target').first();
        let $lengthSlot = $toolbarTarget.find('.datatable-length-slot').first();
        let $searchSlot = $toolbarTarget.find('.datatable-search-slot').first();
        let $lengthControl = $wrapper.find('.dataTables_length, .dt-length').first();
        let $filterControl = $wrapper.find('.dataTables_filter, .dt-search').first();
        let $sourceRow = $lengthControl.closest('.row, .dt-layout-row');

        if (!$sourceRow.length) {
            $sourceRow = $filterControl.closest('.row, .dt-layout-row');
        }

        normalizeToolbarControl($lengthControl, 'length');
        normalizeToolbarControl($filterControl, 'filter');

        if ($lengthControl.length && $lengthSlot.length && !$lengthControl.parent().is($lengthSlot)) {
            $lengthSlot.append($lengthControl);
        }

        if ($filterControl.length && $searchSlot.length && !$filterControl.parent().is($searchSlot)) {
            $searchSlot.append($filterControl);
        }

        if ($sourceRow.length) {
            $sourceRow.hide();
        }
    }

    let dataTable = $('#bookings-table').DataTable({
        responsive: false,
        scrollX: true,
        scrollCollapse: true,
        autoWidth: false,
        pageLength: 10,
        lengthMenu: [5, 10, 25, 50, 100],
        order: [[0, 'asc']],
        initComplete: function () {
            moveTableControlsToHeader(this.api());
        },
        columnDefs: [
            { orderable: false, targets: [1, -1] }
        ]
    });
    let shouldReloadFilteredView = @json(auth()->user()->hasRole('super admin') && !empty($selectedManagerId));

    let baseUrl = "{{ url('animals') }}";
    let storeUrl = "{{ route('animals.store') }}";
    let appUrl = "{{ url('/') }}";
    let imageDeleteBaseUrl = "{{ url('animal-images') }}";

    let animalFormModal = new bootstrap.Modal(document.getElementById('animalFormModal'));
    let animalViewModal = new bootstrap.Modal(document.getElementById('animalViewModal'));

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': "{{ csrf_token() }}",
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json'
        }
    });

    function escapeHtml(text) {
        if (text === null || text === undefined) {
            return '';
        }

        return $('<div>').text(text).html();
    }

    function getImageUrl(path) {
        if (!path) {
            return '';
        }

        if (path.startsWith('http://') || path.startsWith('https://')) {
            return path;
        }

        return appUrl + '/' + path;
    }

    function getTableImage(path) {
        if (!path) {
            return 'N/A';
        }

        return `<img src="${getImageUrl(path)}" class="animal-table-image">`;
    }

    function getProfitBadge(animal) {
        if (animal.profit_loss === null || animal.profit_loss === undefined) {
            return 'N/A';
        }

        return `
            <span class="badge ${animal.profit_class} profit-badge">
                ${animal.formatted_profit_loss}
            </span>
        `;
    }

    function getActionButtons(id) {
        return `
            <div class="d-inline-flex align-items-center action-icons">

                @can('view animals')
                    <button type="button"
                            class="action-icon text-info border-0 bg-transparent p-0 viewAnimalBtn"
                            data-id="${id}"
                            title="View">
                        <i class="bx bx-show"></i>
                    </button>
                @endcan

                @can('update animals')
                    <button type="button"
                            class="action-icon text-warning border-0 bg-transparent p-0 editAnimalBtn"
                            data-id="${id}"
                            title="Edit">
                        <i class="bx bx-edit-alt"></i>
                    </button>
                @endcan

                @can('delete animals')
                    <button type="button"
                            class="action-icon text-danger border-0 bg-transparent p-0 deleteAnimalBtn"
                            data-id="${id}"
                            title="Delete">
                        <i class="bx bx-trash"></i>
                    </button>
                @endcan

            </div>
        `;
    }

    function refreshSerialNumbers() {
        dataTable
            .column(0, { search: 'applied', order: 'applied' })
            .nodes()
            .each(function (cell, index) {
                cell.innerHTML = index + 1;
            });
    }

    function showMessage(type, message) {
        $('#ajaxMessage').html(`
            <div class="alert alert-${type} alert-dismissible fade show" role="alert">
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `);

        setTimeout(function () {
            $('#ajaxMessage .alert').fadeOut();
        }, 3000);
    }

    function clearErrors() {
        $('#formErrors').html('');

        $('#cattleCategoryError').text('');
        $('#animalNameError').text('');
        $('#buyDateError').text('');
        $('#buyPriceError').text('');
        $('#saleDateError').text('');
        $('#salePriceError').text('');
        $('#breedError').text('');
        $('#weightError').text('');
        $('#tagNumberError').text('');
        $('#imagesError').text('');
        $('#notesError').text('');

        $('#cattle_category_id').removeClass('is-invalid');
        $('#animal_name').removeClass('is-invalid');
        $('#buy_date').removeClass('is-invalid');
        $('#buy_price').removeClass('is-invalid');
        $('#sale_date').removeClass('is-invalid');
        $('#sale_price').removeClass('is-invalid');
        $('#breed').removeClass('is-invalid');
        $('#weight').removeClass('is-invalid');
        $('#tag_number').removeClass('is-invalid');
        $('#images').removeClass('is-invalid');
        $('#notes').removeClass('is-invalid');
    }

    function resetForm() {
        $('#animalForm')[0].reset();
        $('#animal_id').val('');
        $('#form_method').val('POST');
        $('#animalModalTitle').text('Add Animal');
        $('#saveAnimalBtn').prop('disabled', false).text('Save');
        $('#existingImages').html('No images found.');
        clearErrors();
    }

    function resetSaveButton() {
        let method = $('#form_method').val();

        $('#saveAnimalBtn').prop('disabled', false);

        if (method === 'PUT') {
            $('#saveAnimalBtn').text('Update');
        } else {
            $('#saveAnimalBtn').text('Save');
        }
    }

    function renderExistingImages(images) {
        if (!images || images.length === 0) {
            $('#existingImages').html('No images found.');
            return;
        }

        let html = '';

        images.forEach(function (image) {
            html += `
                <div class="animal-image-box" id="animal-image-${image.id}">
                    <img src="${getImageUrl(image.image)}" class="animal-preview-image">
                    <button type="button"
                            class="btn btn-danger btn-sm animal-image-delete deleteAnimalImageBtn"
                            data-id="${image.id}">
                        ×
                    </button>
                </div>
            `;
        });

        $('#existingImages').html(html);
    }

    function renderViewImages(images) {
        if (!images || images.length === 0) {
            return 'N/A';
        }

        let html = '';

        images.forEach(function (image) {
            html += `
                <img src="${getImageUrl(image.image)}" class="animal-preview-image me-1 mb-1">
            `;
        });

        return html;
    }

    function getRowData(animal) {
        return [
            '',
            getTableImage(animal.last_image),
            escapeHtml(animal.animal_name),
            escapeHtml(animal.category_title),
            escapeHtml(animal.formatted_expense_per_animal),
            escapeHtml(animal.formatted_buy_price),
            escapeHtml(animal.formatted_total_expense),
            escapeHtml(animal.formatted_sale_price),
            getProfitBadge(animal),
            escapeHtml(animal.tag_number),
            getActionButtons(animal.id)
        ];
    }

    $('#addAnimalBtn').on('click', function () {
        resetForm();
        animalFormModal.show();
    });

    $(document).on('click', '.editAnimalBtn', function () {
        let id = $(this).data('id');

        resetForm();

        $.ajax({
            url: baseUrl + '/' + id + '/edit',
            type: 'GET',
            success: function (response) {
                if (response.status === true) {
                    $('#animal_id').val(response.animal.id);
                    $('#cattle_category_id').val(response.animal.cattle_category_id);
                    $('#animal_name').val(response.animal.animal_name);
                    $('#buy_date').val(response.animal.buy_date);
                    $('#buy_price').val(response.animal.buy_price);
                    $('#sale_date').val(response.animal.sale_date);
                    $('#sale_price').val(response.animal.sale_price);
                    $('#breed').val(response.animal.breed);
                    $('#weight').val(response.animal.weight);
                    $('#tag_number').val(response.animal.tag_number);
                    $('#notes').val(response.animal.notes);

                    renderExistingImages(response.animal.images);

                    $('#form_method').val('PUT');
                    $('#animalModalTitle').text('Edit Animal');
                    $('#saveAnimalBtn').text('Update');

                    animalFormModal.show();
                }
            },
            error: function () {
                showMessage('danger', 'Something went wrong while fetching animal data.');
            }
        });
    });

    $(document).on('click', '.viewAnimalBtn', function () {
        let id = $(this).data('id');

        $.ajax({
            url: baseUrl + '/' + id,
            type: 'GET',
            success: function (response) {
                if (response.status === true) {
                    let animal = response.animal;

                    $('#viewAnimalName').text(animal.animal_name ?? '-');
                    $('#viewCategory').text(animal.category_title ?? 'N/A');
                    $('#viewBuyDate').text(animal.buy_date ?? '-');
                    $('#viewBuyPrice').text(animal.formatted_buy_price);
                    $('#viewPerAnimalExpense').text(animal.formatted_expense_per_animal);
                    $('#viewTotalExpense').text(animal.formatted_total_expense);
                    $('#viewSaleDate').text(animal.sale_date ?? '-');
                    $('#viewSalePrice').text(animal.formatted_sale_price);
                    $('#viewProfitLoss').html(getProfitBadge(animal));
                    $('#viewBreed').text(animal.breed ?? '-');
                    $('#viewWeight').text(animal.weight ?? '-');
                    $('#viewTagNumber').text(animal.tag_number ?? '-');
                    $('#viewNotes').text(animal.notes ?? '-');
                    $('#viewImages').html(renderViewImages(animal.images));

                    animalViewModal.show();
                }
            },
            error: function () {
                showMessage('danger', 'Something went wrong while fetching animal details.');
            }
        });
    });

    $('#animalForm').on('submit', function (e) {
        e.preventDefault();

        clearErrors();

        let id = $('#animal_id').val();
        let method = $('#form_method').val();

        let ajaxUrl = method === 'PUT'
            ? baseUrl + '/' + id
            : storeUrl;

        let formData = new FormData(this);

        $('#saveAnimalBtn').prop('disabled', true).text('Saving...');

        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function (response) {
                if (response.status === true) {

                    let animal = response.animal;

                    if (shouldReloadFilteredView) {
                        window.location.reload();
                        return;
                    }

                    if (method === 'PUT') {
                        let rowSelector = '#animal-row-' + animal.id;
                        let row = dataTable.row(rowSelector);

                        row.data(getRowData(animal)).draw(false);

                        $(row.node()).attr('id', 'animal-row-' + animal.id);

                        showMessage('success', response.message);
                    } else {
                        let newRow = dataTable.row.add(getRowData(animal)).draw(false).node();

                        $(newRow).attr('id', 'animal-row-' + animal.id);

                        showMessage('success', response.message);
                    }

                    refreshSerialNumbers();

                    animalFormModal.hide();
                    resetForm();
                }
            },
            error: function (xhr) {
                resetSaveButton();

                if (xhr.status === 422) {
                    let errors = xhr.responseJSON.errors;

                    if (errors.cattle_category_id) {
                        $('#cattle_category_id').addClass('is-invalid');
                        $('#cattleCategoryError').text(errors.cattle_category_id[0]);
                    }

                    if (errors.animal_name) {
                        $('#animal_name').addClass('is-invalid');
                        $('#animalNameError').text(errors.animal_name[0]);
                    }

                    if (errors.buy_date) {
                        $('#buy_date').addClass('is-invalid');
                        $('#buyDateError').text(errors.buy_date[0]);
                    }

                    if (errors.buy_price) {
                        $('#buy_price').addClass('is-invalid');
                        $('#buyPriceError').text(errors.buy_price[0]);
                    }

                    if (errors.sale_date) {
                        $('#sale_date').addClass('is-invalid');
                        $('#saleDateError').text(errors.sale_date[0]);
                    }

                    if (errors.sale_price) {
                        $('#sale_price').addClass('is-invalid');
                        $('#salePriceError').text(errors.sale_price[0]);
                    }

                    if (errors.breed) {
                        $('#breed').addClass('is-invalid');
                        $('#breedError').text(errors.breed[0]);
                    }

                    if (errors.weight) {
                        $('#weight').addClass('is-invalid');
                        $('#weightError').text(errors.weight[0]);
                    }

                    if (errors.tag_number) {
                        $('#tag_number').addClass('is-invalid');
                        $('#tagNumberError').text(errors.tag_number[0]);
                    }

                    if (errors.notes) {
                        $('#notes').addClass('is-invalid');
                        $('#notesError').text(errors.notes[0]);
                    }

                    if (errors.images || errors['images.0']) {
                        $('#images').addClass('is-invalid');

                        if (errors.images) {
                            $('#imagesError').text(errors.images[0]);
                        } else {
                            $('#imagesError').text(errors['images.0'][0]);
                        }
                    }
                } else if (xhr.status === 403) {
                    $('#formErrors').html(`
                        <div class="alert alert-danger">
                            Unauthorized access.
                        </div>
                    `);
                } else {
                    $('#formErrors').html(`
                        <div class="alert alert-danger">
                            Something went wrong. Please try again.
                        </div>
                    `);
                }
            }
        });
    });

    $(document).on('click', '.deleteAnimalBtn', function () {
        let id = $(this).data('id');

        if (!confirm('Are you sure you want to delete this animal? Images will also be deleted.')) {
            return;
        }

        $.ajax({
            url: baseUrl + '/' + id,
            type: 'POST',
            data: {
                _method: 'DELETE'
            },
            success: function (response) {
                if (response.status === true) {
                    if (shouldReloadFilteredView) {
                        window.location.reload();
                        return;
                    }

                    let rowSelector = '#animal-row-' + id;

                    dataTable.row(rowSelector).remove().draw(false);

                    refreshSerialNumbers();

                    showMessage('success', response.message);
                }
            },
            error: function (xhr) {
                if (xhr.status === 403) {
                    showMessage('danger', 'Unauthorized access.');
                } else {
                    showMessage('danger', 'Something went wrong while deleting animal.');
                }
            }
        });
    });

    $(document).on('click', '.deleteAnimalImageBtn', function () {
        let id = $(this).data('id');

        if (!confirm('Are you sure you want to delete this image?')) {
            return;
        }

        $.ajax({
            url: imageDeleteBaseUrl + '/' + id,
            type: 'POST',
            data: {
                _method: 'DELETE'
            },
            success: function (response) {
                if (response.status === true) {
                    if (shouldReloadFilteredView) {
                        window.location.reload();
                        return;
                    }

                    $('#animal-image-' + id).remove();

                    if ($('#existingImages .animal-image-box').length === 0) {
                        $('#existingImages').html('No images found.');
                    }

                    showMessage('success', response.message);
                }
            },
            error: function () {
                showMessage('danger', 'Something went wrong while deleting image.');
            }
        });
    });

    dataTable.on('order.dt search.dt draw.dt', function () {
        refreshSerialNumbers();
    });

});
</script>
@endpush
