

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

    .action-icons {
        gap: 10px;
    }

    .action-icon {
        font-size: 20px;
        cursor: pointer;
        text-decoration: none;
        line-height: 1;
    }

    .action-icon:hover {
        opacity: 0.8;
    }

    .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 d-flex justify-content-between align-items-center">
            <h5 class="mb-0">Animals</h5>

            <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('create animals')): ?>
                <button type="button" class="btn btn-primary" id="addAnimalBtn">
                    Add Animal
                </button>
            <?php endif; ?>
        </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>Name</th>
                            <th>Category</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>
                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__currentLoopData = $animals; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $animal): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <?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';
                                    }
                                }
                            ?>

                            <tr id="animal-row-<?php echo e($animal->id); ?>">
                                <td><?php echo e($loop->iteration); ?></td>

                                <td>
                                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($lastImage): ?>
                                        <img src="<?php echo e(asset($lastImage->image)); ?>" class="animal-table-image">
                                    <?php else: ?>
                                        N/A
                                    <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                                </td>

                                <td><?php echo e($animal->animal_name); ?></td>
                                <td><?php echo e($animal->category->title ?? 'N/A'); ?></td>
                                <td><?php echo e(number_format($animal->expense_per_animal ?? 0, 2)); ?></td>
                                <td><?php echo e(number_format($animal->buy_price ?? 0, 2)); ?></td>
                                <td><?php echo e(number_format($animal->total_expense ?? 0, 2)); ?></td>

                                <td>
                                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if(!is_null($animal->sale_price) && $animal->sale_price !== ''): ?>
                                        <?php echo e(number_format($animal->sale_price, 2)); ?>

                                    <?php else: ?>
                                        N/A
                                    <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                                </td>

                                <td>
                                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if(is_null($profitLoss)): ?>
                                        N/A
                                    <?php else: ?>
                                        <span class="badge <?php echo e($profitClass); ?> profit-badge">
                                            <?php echo e($profitText); ?>

                                        </span>
                                    <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                                </td>

                                <td><?php echo e($animal->tag_number ?? 'N/A'); ?></td>

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

                                        <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('view animals')): ?>
                                            <button type="button"
                                                    class="action-icon text-info border-0 bg-transparent p-0 viewAnimalBtn"
                                                    data-id="<?php echo e($animal->id); ?>"
                                                    title="View">
                                                <i class="bx bx-show"></i>
                                            </button>
                                        <?php endif; ?>

                                        <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('update animals')): ?>
                                            <button type="button"
                                                    class="action-icon text-warning border-0 bg-transparent p-0 editAnimalBtn"
                                                    data-id="<?php echo e($animal->id); ?>"
                                                    title="Edit">
                                                <i class="bx bx-edit-alt"></i>
                                            </button>
                                        <?php endif; ?>

                                        <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('delete animals')): ?>
                                            <button type="button"
                                                    class="action-icon text-danger border-0 bg-transparent p-0 deleteAnimalBtn"
                                                    data-id="<?php echo e($animal->id); ?>"
                                                    title="Delete">
                                                <i class="bx bx-trash"></i>
                                            </button>
                                        <?php endif; ?>

                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                    </tbody>

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


<div class="modal fade" id="animalFormModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <form id="animalForm" enctype="multipart/form-data">
            <?php echo csrf_field(); ?>

            <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>
                                <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__currentLoopData = $categories; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $category): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <option value="<?php echo e($category->id); ?>">
                                        <?php echo e($category->title); ?>

                                    </option>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                            </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>


<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>

<?php $__env->stopSection(); ?>

<?php $__env->startPush('script'); ?>
<script>
$(document).ready(function () {

    let dataTable = $('#bookings-table').DataTable({
        responsive: false,
        scrollX: true,
        pageLength: 10,
        lengthMenu: [5, 10, 25, 50, 100],
        order: [[0, 'asc']],
        columnDefs: [
            { orderable: false, targets: [1, -1] }
        ]
    });

    let baseUrl = "<?php echo e(url('animals')); ?>";
    let storeUrl = "<?php echo e(route('animals.store')); ?>";
    let appUrl = "<?php echo e(url('/')); ?>";
    let imageDeleteBaseUrl = "<?php echo e(url('animal-images')); ?>";

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

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': "<?php echo e(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">

                <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('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>
                <?php endif; ?>

                <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('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>
                <?php endif; ?>

                <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('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>
                <?php endif; ?>

            </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 (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) {
                    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) {
                    $('#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>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH F:\xampp\htdocs\Cattle-Farm-Management-System\resources\views/animals/index.blade.php ENDPATH**/ ?>