@extends('layouts.app')

@section('content')
<style>
    .error-text {
        color: #ff3e1d;
        font-size: 13px;
        margin-top: 5px;
    }

    .expense-categories-table th,
    .expense-categories-table td {
        vertical-align: middle;
    }

    .expense-categories-table .title-col {
        text-align: left;
        min-width: 180px;
        max-width: 240px;
        white-space: normal;
        word-break: break-word;
    }

    .expense-categories-table .amount-col {
        min-width: 140px;
        white-space: nowrap;
    }

    .expense-categories-table .date-col {
        min-width: 120px;
        white-space: nowrap;
    }

    .expense-categories-table .action-col {
        min-width: 180px;
        white-space: nowrap;
    }
</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">Expense Categories</h5>
                </div>

                <div class="datatable-toolbar-target">
                    <div class="datatable-length-slot"></div>

                    <div class="datatable-manager-slot">
                        @include('partials.manager-filter', ['filterId' => 'expense-categories-manager-filter'])
                    </div>

                    <div class="datatable-search-slot"></div>
                </div>

                <div class="datatable-header-action text-end">
                    @can('create expense categories')
                        <button type="button" class="btn btn-primary" id="addCategoryBtn">
                            Add Category
                        </button>
                    @endcan
                </div>
            </div>

            <hr>
        </div>

        <div class="card-body">

            <div id="ajaxMessage"></div>

            <div class="table-responsive">
                <table id="bookings-table" class="table table-bordered align-middle text-center expense-categories-table">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th class="title-col">Title</th>
                            <th class="amount-col">Total Expense</th>
                            <th class="date-col">Created At</th>
                            <th class="action-col" width="220">Action</th>
                        </tr>
                    </thead>

                    <tbody>
                        @foreach($categories as $key => $category)
                            <tr id="category-row-{{ $category->id }}">
                                <td>{{ $key + 1 }}</td>

                                <td class="title-col">{{ $category->title ?? 'N/A' }}</td>

                                <td class="amount-col">
                                    Rs {{ number_format($category->total_expense ?? 0, 2) }}
                                </td>

                                <td class="date-col">
                                    {{ $category->created_at ? $category->created_at->format('d M Y') : '-' }}
                                </td>

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

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

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

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

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

        </div>
    </div>

</div>

{{-- Add / Edit Modal --}}
<div class="modal fade" id="categoryFormModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form id="categoryForm">
            @csrf

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

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

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

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

                    <tr>
                        <th>Total Expense</th>
                        <td id="viewTotalExpense"></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>

@endsection

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

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

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

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

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

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

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

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

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

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

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

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

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

    let dataTable = $('#bookings-table').DataTable({
        responsive: false,
        scrollX: true,
        scrollCollapse: true,
        autoWidth: false,
        pageLength: 50,
        lengthMenu: [5, 10, 25, 50, 100],
        order: [[0, 'asc']],
        initComplete: function () {
            moveTableControlsToHeader(this.api());
        },
        columnDefs: [
            { width: '60px', targets: 0 },
            { width: '220px', targets: 1 },
            { width: '140px', targets: 2 },
            { width: '120px', targets: 3 },
            { width: '180px', targets: 4, orderable: false }
        ]
    });

    dataTable.columns.adjust().draw(false);

    let shouldReloadFilteredView = @json(auth()->user()->hasRole('super admin') && !empty($selectedManagerId));

    let baseUrl = "{{ url('expense-categories') }}";
    let storeUrl = "{{ route('expense-categories.store') }}";

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

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

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

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

    function formatAmount(amount) {
        let numericAmount = Number(amount ?? 0);

        if (Number.isNaN(numericAmount)) {
            numericAmount = 0;
        }

        return 'Rs ' + numericAmount.toLocaleString('en-US', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
        });
    }

    function getFormattedTotalExpense(category) {
        if (category.formatted_total_expense) {
            return escapeHtml(category.formatted_total_expense);
        }

        if (category.total_expense !== undefined && category.total_expense !== null) {
            return formatAmount(category.total_expense);
        }

        return formatAmount(0);
    }

    function getFormattedCreatedAt(category) {
        if (category.created_at) {
            return escapeHtml(category.created_at);
        }

        if (category.formatted_created_at) {
            return escapeHtml(category.formatted_created_at);
        }

        return '-';
    }

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

                @can('view expense 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>
                @endcan

                @can('update expense 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>
                @endcan

                @can('delete expense 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>
                @endcan

            </div>
        `;
    }

    function getRowData(category) {
        return [
            '',
            escapeHtml(category.title ?? 'N/A'),
            getFormattedTotalExpense(category),
            getFormattedCreatedAt(category),
            getActionButtons(category.id)
        ];
    }

    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('');
        $('#title').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');
        }
    }

    $('#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);
                    $('#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 ?? 'N/A');
                    $('#viewTotalExpense').text(
                        category.formatted_total_expense
                            ? category.formatted_total_expense
                            : formatAmount(category.total_expense ?? 0)
                    );
                    $('#viewUser').text(category.user_name ?? '-');
                    $('#viewCreatedAt').text(category.created_at ?? category.formatted_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]);
                    }
                } 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 you want to delete this category?')) {
            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>
@endpush
