<?php $__env->startSection('content'); ?>

<style>
    .cattle-categories-table th.title-col,
    .cattle-categories-table td.title-col {
        width: 180px !important;
        min-width: 180px !important;
        max-width: 180px !important;
        white-space: normal !important;
        word-break: break-word;
        text-align: left;
    }
</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">Cattle Name</h5>
                </div>

                <div class="datatable-toolbar-target">
                    <div class="datatable-length-slot"></div>
                    <div class="datatable-manager-slot">
                        <?php echo $__env->make('partials.manager-filter', ['filterId' => 'cattle-categories-manager-filter'], \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
                    </div>
                    <div class="datatable-search-slot"></div>
                </div>

                <div class="datatable-header-action text-end">
                    <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('create categories')): ?>
                        <button type="button" class="btn btn-primary" id="addCategoryBtn">
                            Add Category
                        </button>
                    <?php endif; ?>
                </div>
            </div>
            <hr />
        </div>

        <div class="card-body">

            <div id="ajaxMessage"></div>
            <div class="table-responsive custom-table-responsive">
                <table id="bookings-table" class="table table-bordered align-middle text-center nowrap cattle-categories-table">
                    <thead>
                        <tr>
                            
                           <th style="min-width: 200px;">Cattle Name</th>
                            
                            <th>T.Animals</th>
                            <th>T.Buy Price</th>
                            <th>T.Selling Price</th>
                            <th>Expense</th>
                            <th>T.Expense</th>
                            <th>T.Profit</th>
                            <th>Created At</th>
                            <th width="280">Action</th>
                        </tr>
                    </thead>

                    <tbody>
                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__currentLoopData = $categories; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $category): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <?php
                                $profit = $category->total_profit ?? 0;

                                if ($profit > 0) {
                                    $profitText = '+' . number_format($profit, 2);
                                    $profitClass = 'bg-success';
                                } elseif ($profit < 0) {
                                    $profitText = number_format($profit, 2);
                                    $profitClass = 'bg-danger';
                                } else {
                                    $profitText = number_format($profit, 2);
                                    $profitClass = 'bg-secondary';
                                }
                            ?>

                            <tr id="category-row-<?php echo e($category->id); ?>">
                                

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

                                

                                <td><?php echo e($category->animals_count ?? 0); ?></td>

                                <td><?php echo e(number_format($category->total_buy_price ?? 0, 2)); ?></td>

                                <td><?php echo e(number_format($category->total_sale_price ?? 0, 2)); ?></td>

                                <td><?php echo e(number_format($category->total_expense_amount ?? 0, 2)); ?></td>

                                <td><?php echo e(number_format($category->grand_total_expense ?? 0, 2)); ?></td>

                                <td>
                                    <span class="badge <?php echo e($profitClass); ?> profit-badge">
                                        <?php echo e($profitText); ?>

                                    </span>
                                </td>

                                <td>
                                    <?php echo e($category->created_at ? $category->created_at->format('d M Y') : '-'); ?>

                                </td>

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

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

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

                                        <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('delete categories')): ?>
                                            <button type="button"
                                                    class="action-icon text-danger border-0 bg-transparent p-0 deleteCategoryBtn"
                                                    data-id="<?php echo e($category->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="categoryFormModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form id="categoryForm">
            <?php echo csrf_field(); ?>

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

            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="categoryModalTitle">Add Category</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="mb-3">
                        <label class="form-label">
                            Cattle Name <span class="text-danger">*</span>
                        </label>

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

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

                    <div class="mb-3">
                        <label class="form-label">Start Date</label>

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

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

                    <div class="mb-3">
                        <label class="form-label">End Date</label>

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

                        <div class="error-text" id="endDateError"></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="saveCategoryBtn">
                        Save
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>


<div class="modal fade" id="categoryViewModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">

            <div class="modal-header">
                <h5 class="modal-title">View Cattle Category</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="35%">Cattle Name</th>
                        <td id="viewTitle"></td>
                    </tr>

                    <tr>
                        <th>Start Date</th>
                        <td id="viewStartDate"></td>
                    </tr>

                    <tr>
                        <th>End Date</th>
                        <td id="viewEndDate"></td>
                    </tr>

                    <tr>
                        <th>Total Animals</th>
                        <td id="viewTotalAnimals"></td>
                    </tr>

                    <tr>
                        <th>Total Buy Price</th>
                        <td id="viewTotalBuyPrice"></td>
                    </tr>

                    <tr>
                        <th>Total Selling Price</th>
                        <td id="viewTotalSalePrice"></td>
                    </tr>

                    <tr>
                        <th>Category Expense</th>
                        <td id="viewCategoryExpense"></td>
                    </tr>

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

                    <tr>
                        <th>Total Profit</th>
                        <td id="viewTotalProfit"></td>
                    </tr>

                    <tr>
                        <th>Created By</th>
                        <td id="viewUser"></td>
                    </tr>

                    <tr>
                        <th>Created At</th>
                        <td id="viewCreatedAt"></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 () {
    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: [
            { width: '320px', targets: 0 },
            { orderable: false, targets: -1 }
        ]
    });
    dataTable.columns.adjust().draw(false);
    let shouldReloadFilteredView = <?php echo json_encode(auth()->user()->hasRole('super admin') && !empty($selectedManagerId), 15, 512) ?>;

    let baseUrl = "<?php echo e(url('cattle-categories')); ?>";
    let storeUrl = "<?php echo e(route('cattle-categories.store')); ?>";

    let categoryFormModal = new bootstrap.Modal(document.getElementById('categoryFormModal'));
    let categoryViewModal = new bootstrap.Modal(document.getElementById('categoryViewModal'));

    $.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 getProfitBadge(category) {
        return `
            <span class="badge ${category.profit_class} profit-badge">
                ${category.formatted_total_profit}
            </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 categories')): ?>
                    <button type="button"
                            class="action-icon text-info border-0 bg-transparent p-0 viewCategoryBtn"
                            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 categories')): ?>
                    <button type="button"
                            class="action-icon text-warning border-0 bg-transparent p-0 editCategoryBtn"
                            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 categories')): ?>
                    <button type="button"
                            class="action-icon text-danger border-0 bg-transparent p-0 deleteCategoryBtn"
                            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('');

        $('#titleError').text('');
        $('#startDateError').text('');
        $('#endDateError').text('');

        $('#title').removeClass('is-invalid');
        $('#start_date').removeClass('is-invalid');
        $('#end_date').removeClass('is-invalid');
    }

    function resetForm() {
        $('#categoryForm')[0].reset();
        $('#category_id').val('');
        $('#form_method').val('POST');
        $('#categoryModalTitle').text('Add Category');
        $('#saveCategoryBtn').prop('disabled', false).text('Save');
        clearErrors();
    }

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

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

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

    function getRowData(category) {
        return [
            '',
            escapeHtml(category.title),
            escapeHtml(category.formatted_start_date),
            escapeHtml(category.formatted_end_date),
            category.animals_count,
            escapeHtml(category.formatted_total_buy_price),
            escapeHtml(category.formatted_total_sale_price),
            escapeHtml(category.formatted_total_expense_amount),
            escapeHtml(category.formatted_grand_total_expense),
            getProfitBadge(category),
            escapeHtml(category.created_at),
            getActionButtons(category.id)
        ];
    }

    $('#addCategoryBtn').on('click', function () {
        resetForm();
        categoryFormModal.show();
    });

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

        resetForm();

        $.ajax({
            url: baseUrl + '/' + id + '/edit',
            type: 'GET',
            success: function (response) {
                if (response.status === true) {
                    $('#category_id').val(response.category.id);
                    $('#title').val(response.category.title);
                    $('#start_date').val(response.category.start_date);
                    $('#end_date').val(response.category.end_date);

                    $('#form_method').val('PUT');
                    $('#categoryModalTitle').text('Edit Category');
                    $('#saveCategoryBtn').text('Update');

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

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

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

                    $('#viewTitle').text(category.title);
                    $('#viewStartDate').text(category.formatted_start_date);
                    $('#viewEndDate').text(category.formatted_end_date);
                    $('#viewTotalAnimals').text(category.animals_count);
                    $('#viewTotalBuyPrice').text(category.formatted_total_buy_price);
                    $('#viewTotalSalePrice').text(category.formatted_total_sale_price);
                    $('#viewCategoryExpense').text(category.formatted_total_expense_amount);
                    $('#viewGrandTotalExpense').text(category.formatted_grand_total_expense);
                    $('#viewTotalProfit').html(getProfitBadge(category));
                    $('#viewUser').text(category.user_name);
                    $('#viewCreatedAt').text(category.created_at);

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

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

        clearErrors();

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

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

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

        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: $(this).serialize(),
            success: function (response) {
                if (response.status === true) {
                    let category = response.category;

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

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

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

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

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

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

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

                    refreshSerialNumbers();

                    categoryFormModal.hide();
                    resetForm();

                    dataTable.columns.adjust().draw(false);
                }
            },
            error: function (xhr) {
                resetSaveButton();

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

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

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

                    if (errors.end_date) {
                        $('#end_date').addClass('is-invalid');
                        $('#endDateError').text(errors.end_date[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', '.deleteCategoryBtn', function () {
        let id = $(this).data('id');

        if (!confirm('Are you sure?')) {
            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 = '#category-row-' + id;

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

                    refreshSerialNumbers();

                    showMessage('success', response.message);

                    dataTable.columns.adjust().draw(false);
                }
            },
            error: function (xhr) {
                if (xhr.status === 403) {
                    showMessage('danger', 'Unauthorized access.');
                } else {
                    showMessage('danger', 'Something went wrong while deleting category.');
                }
            }
        });
    });

    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\resources\views/cattle-categories/index.blade.php ENDPATH**/ ?>