

<?php $__env->startSection('content'); ?>
<style>
    .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;
    }
</style>

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

    <div class="card">
        <div class="card-header">
            <div class="row align-items-center">
                <div class="col-md-6">
                    <h5 class="mb-0">Expenses</h5>
                </div>

                <div class="col-md-6 text-end">
                    <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('create expenses')): ?>
                        <button type="button" class="btn btn-primary" id="addExpenseBtn">
                            Add Expense
                        </button>
                    <?php endif; ?>
                </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 class="table-light">
                        <tr>
                            <th>#</th>
                            <th>Cattle Category</th>
                            <th>Expense Category</th>
                            <th>Title</th>
                            <th>Date</th>
                            <th>Amount</th>
                            <th width="220">Action</th>
                        </tr>
                    </thead>

                    <tbody>
                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__currentLoopData = $expenses; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $expense): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <tr id="expense-row-<?php echo e($expense->id); ?>">
                                <td><?php echo e($key + 1); ?></td>
                                <td><?php echo e($expense->cattleCategory->title ?? '-'); ?></td>
                                <td><?php echo e($expense->expenseCategory->title ?? '-'); ?></td>
                                <td><?php echo e($expense->title ?? '-'); ?></td>
                                <td>
                                    <?php echo e($expense->expense_date ? \Carbon\Carbon::parse($expense->expense_date)->format('d M Y') : '-'); ?>

                                </td>
                                <td><?php echo e(number_format($expense->amount, 2)); ?></td>
                                <td>
                                    <div class="d-inline-flex align-items-center action-icons">

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

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

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

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

            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="expenseModalTitle">Add Expense</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 Cattle Category</option>
                                <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__currentLoopData = $cattleCategories; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $cattleCategory): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <option value="<?php echo e($cattleCategory->id); ?>">
                                        <?php echo e($cattleCategory->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">
                                Expense Category <span class="text-danger">*</span>
                            </label>

                            <select name="expense_category_id" id="expense_category_id" class="form-control">
                                <option value="">Select Expense Category</option>
                                <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__currentLoopData = $expenseCategories; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $expenseCategory): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <option value="<?php echo e($expenseCategory->id); ?>">
                                        <?php echo e($expenseCategory->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="expenseCategoryError"></div>
                        </div>

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

                    <tr>
                        <th>Title</th>
                        <td id="viewTitle"></td>
                    </tr>

                    <tr>
                        <th>Date</th>
                        <td id="viewDate"></td>
                    </tr>

                    <tr>
                        <th>Amount</th>
                        <td id="viewAmount"></td>
                    </tr>

                    <tr>
                        <th>Description</th>
                        <td id="viewDescription"></td>
                    </tr>

                    <tr>
                        <th>Created By</th>
                        <td id="viewUser"></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 }
        ]
    });

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

    let expenseFormModal = new bootstrap.Modal(document.getElementById('expenseFormModal'));
    let expenseViewModal = new bootstrap.Modal(document.getElementById('expenseViewModal'));

    $.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 getActionButtons(id) {
        return `
            <div class="d-inline-flex align-items-center action-icons">

                <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('view expenses')): ?>
                    <button type="button"
                            class="action-icon text-info border-0 bg-transparent p-0 viewExpenseBtn"
                            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 expenses')): ?>
                    <button type="button"
                            class="action-icon text-warning border-0 bg-transparent p-0 editExpenseBtn"
                            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 expenses')): ?>
                    <button type="button"
                            class="action-icon text-danger border-0 bg-transparent p-0 deleteExpenseBtn"
                            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('');
        $('#expenseCategoryError').text('');
        $('#titleError').text('');
        $('#expenseDateError').text('');
        $('#amountError').text('');
        $('#descriptionError').text('');

        $('#cattle_category_id').removeClass('is-invalid');
        $('#expense_category_id').removeClass('is-invalid');
        $('#title').removeClass('is-invalid');
        $('#expense_date').removeClass('is-invalid');
        $('#amount').removeClass('is-invalid');
        $('#description').removeClass('is-invalid');
    }

    function resetForm() {
        $('#expenseForm')[0].reset();
        $('#expense_id').val('');
        $('#form_method').val('POST');
        $('#expenseModalTitle').text('Add Expense');
        $('#saveExpenseBtn').prop('disabled', false).text('Save');
        clearErrors();
    }

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

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

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

    $('#addExpenseBtn').on('click', function () {
        resetForm();
        expenseFormModal.show();
    });

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

        resetForm();

        $.ajax({
            url: baseUrl + '/' + id + '/edit',
            type: 'GET',
            success: function (response) {
                if (response.status === true) {
                    $('#expense_id').val(response.expense.id);
                    $('#cattle_category_id').val(response.expense.cattle_category_id);
                    $('#expense_category_id').val(response.expense.expense_category_id);
                    $('#title').val(response.expense.title);
                    $('#expense_date').val(response.expense.expense_date);
                    $('#amount').val(response.expense.amount);
                    $('#description').val(response.expense.description);

                    $('#form_method').val('PUT');
                    $('#expenseModalTitle').text('Edit Expense');
                    $('#saveExpenseBtn').text('Update');

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

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

        $.ajax({
            url: baseUrl + '/' + id,
            type: 'GET',
            success: function (response) {
                if (response.status === true) {
                    $('#viewCattleCategory').text(response.expense.cattle_category_title);
                    $('#viewExpenseCategory').text(response.expense.expense_category_title);
                    $('#viewTitle').text(response.expense.title);
                    $('#viewDate').text(response.expense.formatted_date);
                    $('#viewAmount').text(response.expense.formatted_amount);
                    $('#viewDescription').text(response.expense.description);
                    $('#viewUser').text(response.expense.user_name);

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

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

        clearErrors();

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

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

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

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

                    let expense = response.expense;

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

                        row.data([
                            '',
                            escapeHtml(expense.cattle_category_title),
                            escapeHtml(expense.expense_category_title),
                            escapeHtml(expense.title),
                            escapeHtml(expense.formatted_date),
                            escapeHtml(expense.formatted_amount),
                            getActionButtons(expense.id)
                        ]).draw(false);

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

                        showMessage('success', response.message);
                    } else {
                        let newRow = dataTable.row.add([
                            '',
                            escapeHtml(expense.cattle_category_title),
                            escapeHtml(expense.expense_category_title),
                            escapeHtml(expense.title),
                            escapeHtml(expense.formatted_date),
                            escapeHtml(expense.formatted_amount),
                            getActionButtons(expense.id)
                        ]).draw(false).node();

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

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

                    refreshSerialNumbers();

                    expenseFormModal.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.expense_category_id) {
                        $('#expense_category_id').addClass('is-invalid');
                        $('#expenseCategoryError').text(errors.expense_category_id[0]);
                    }

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

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

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

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

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

        $.ajax({
            url: baseUrl + '/' + id,
            type: 'POST',
            data: {
                _method: 'DELETE'
            },
            success: function (response) {
                if (response.status === true) {
                    let rowSelector = '#expense-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 expense.');
                }
            }
        });
    });

    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/expenses/index.blade.php ENDPATH**/ ?>