@extends('schoolLayout.app')
@section('content')

    @if (session('error'))
        <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4" role="alert">
            <strong class="font-bold">Error:</strong>
            <span class="block sm:inline">{{ session('error') }}</span>
        </div>
    @endif

    @if (session('success'))
        <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative mb-4" role="alert">
            <strong class="font-bold">Success:</strong>
            <span class="block sm:inline">{{ session('success') }}</span>
        </div>
    @endif


    <div class="bg-[#f9fafc] min-h-screen px-8 py-4">
        <!-- Top Section: Tabs & Button -->
        <div class="flex justify-between items-center">
            <!-- Tabs:-->
            <div class="flex space-x-4 w-[50%]">
                <button class="tab-btn pb-3 text-gray-700 font-semibold"
                    onclick="window.location.href='{{ route('show.expense.categories') }}'">
                    Expense Categories
                </button>
                <button class="tab-btn px-4 pb-3 bg-white py-2 border-b-2 border-blue-500 font-semibold text-blue-500">
                    All Expenses
                </button>
            </div>
            <!-- New Staff Member Button -->
            <button class="px-4 py-2 bg-[#0197FF] flex items-center gap-x-4 text-white rounded-lg"
                onclick="window.location.href = '{{ route('add.expenses') }}'">
                <img src="{{ asset('assets/new.png') }}" alt="icon" />
                <span>Create New Expense</span>
            </button>
        </div>

        <div class="border border-gray-200 rounded-lg mt-4">
            <!-- Filters Section -->
            <div class="bg-white p-3 flex justify-between rounded-lg flex-wrap gap-4">
                <div class="relative  w-[50%] rounded-lg">
                    <div class="border border-gray-200 rounded-sm bg-white flex items-center px-4">
                        <span class="text-gray-500">
                            <img src="{{ asset('assets/search.png') }}" alt="icon" />
                        </span>
                        <input type="text" placeholder="Search Description..." name="search_query" id="search"
                            onkeyup="fetchExpenseData()"
                            class="w-full px-4 pr-8 py-2 text-sm border-none rounded-lg focus:outline-none" />
                    </div>
                </div>
                <div class="flex gap-x-2 items-center">
                    <input type="date" class="p-2 border rounded-lg w-full" name="date_filter" id="date_filter"
                        onchange="fetchExpenseData()" />
                    <select class="border p-2 rounded-lg" name="category_filter" id="category_filter"
                        onchange="fetchExpenseData()">
                        <option value="">All Categories</option>
                        @if ($categories)
                            @foreach ($categories as $category)
                                <option value="{{ $category->expense_account_id }}">{{ $category->expense_categorie->name }}
                                </option>
                            @endforeach
                        @endif
                    </select>
                    <select class="border p-2 rounded-lg" name="amount_filter" id="amount_filter"
                        onchange="fetchExpenseData()">
                        <option value="">All Amounts</option>
                         @if ($amounts)
                            @foreach ($amounts as $amount)
                                <option value="{{ $amount->amount }}">{{ $amount->amount }}</option>
                            @endforeach
                        @endif 
                    </select>
                </div>
            </div>
            <div class=" relative bg-white ">
                <div class="" id="show-expense">
                    @include('expense.allExpSearch', [
                        'expenses' => $expenses,
                        'categories' => $categories,
                    ])
                </div>
                {{ $expenses->links('vendor.pagination.custom-pagination') }}
            </div>
        </div>
    </div>

    <!-- Edit Expense Modal -->
    <div id="editExpenseModal"
        class="hidden fixed inset-0 z-50 overflow-auto bg-black bg-opacity-50 flex items-center justify-center">
        <div class="bg-white rounded-lg shadow-lg w-11/12 md:w-1/2 lg:w-1/3 p-6">
            <div class="flex justify-between items-center pb-4">
                <h5 class="text-lg font-semibold">Edit Expense</h5>
                <button type="button" class="text-gray-500 hover:text-gray-700" onclick="closeModal()">
                    <span class="text-2xl">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="editExpenseForm" action="{{ route('expenses.update', ['id' => ':id']) }}" method="POST">
                    @csrf
                    @method('PUT')
                    <div class="mb-4">
                        <label for="editExpenseHead" class="block text-sm font-medium text-gray-700">Expense Head</label>
                        <select name="expense_head" id="editExpenseHead"
                            class="w-full p-2 border bg-[#F9FAFB] rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                            required>
                            <option value="">Select Category</option>
                            @if ($categories)
                                @foreach ($categories as $category)
                                    <option value="{{ $category->id }}">{{ $category->name }}</option>
                                @endforeach
                            @endif
                        </select>
                    </div>
                    <div class="mb-4">
                        <label for="editExpenseDate" class="block text-sm font-medium text-gray-700">Date</label>
                        <input type="date" name="expense_date" id="editExpenseDate"
                            class="w-full p-2 border bg-[#F9FAFB] rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                            required>
                    </div>
                    <div class="mb-4">
                        <label for="editExpenseAmount" class="block text-sm font-medium text-gray-700">Amount</label>
                        <input type="number" name="expense_amount" id="editExpenseAmount" placeholder="0.00"
                            class="w-full p-2 bg-[#F9FAFB] border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                            required>
                    </div>
                    <div class="mb-4">
                        <label for="editExpenseDescription"
                            class="block text-sm font-medium text-gray-700">Description</label>
                        <textarea name="expense_description" id="editExpenseDescription"
                            class="w-full p-2 bg-[#F9FAFB] border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"></textarea>
                    </div>
                    <div class="flex justify-end">
                        <button type="button" class="px-4 py-2 bg-gray-500 text-white rounded-md hover:bg-gray-600"
                            onclick="closeModal()">Close</button>
                        <button type="submit"
                            class="ml-2 px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600">Save changes</button>
                    </div>
                </form>
            </div>
        </div>
    </div>


@endsection
@section('script')
    <script>
        function toggleDropdown(button) {
            document.querySelectorAll(".action-dropdown").forEach((dropdown) => {
                if (dropdown !== button.nextElementSibling) {
                    dropdown.classList.add("hidden");
                }
            });

            button.nextElementSibling.classList.toggle("hidden");
        }

        document.addEventListener("click", function(event) {
            if (!event.target.closest(".action-btn")) {
                document.querySelectorAll(".action-dropdown").forEach((dropdown) => {
                    dropdown.classList.add("hidden");
                });
            }
        });

        // Function to open the edit modal and populate the form
        function openEditModal(id, categoryName, date, amount, description) {
            // Set the form action URL with the correct ID
            const formAction = document.getElementById('editExpenseForm').action.replace(':id', id);
            document.getElementById('editExpenseForm').action = formAction;

            // Populate the form fields with the data
            document.getElementById('editExpenseHead').value = categoryName;
            document.getElementById('editExpenseDate').value = date;
            document.getElementById('editExpenseAmount').value = amount;
            document.getElementById('editExpenseDescription').value = description;

            // Show the modal
            document.getElementById('editExpenseModal').classList.remove('hidden');
        }

        // Function to close the modal
        function closeModal() {
            document.getElementById('editExpenseModal').classList.add('hidden');
        }

        // Close the modal if the user clicks outside of it
        window.onclick = function(event) {
            const modal = document.getElementById('editExpenseModal');
            if (event.target === modal) {
                closeModal();
            }
        };

        function deleteExpense(element) {
            const id = element.getAttribute('data-id');
            if (confirm('Are you sure you want to delete this expense?')) {
                window.location.href = '/account/expenses-delete/' + id;
            }

        }

        // search Student Functionality
        function fetchExpenseData() {
            let search = document.getElementById("search").value;
            let date_filter = document.getElementById("date_filter").value;
            let category_filter = document.getElementById("category_filter").value;
            let amount_filter = document.getElementById("amount_filter").value;

            $.ajax({
                url: "{{ route('show.expenses') }}",
                method: "GET",
                data: {
                    search_query: search,
                    date_filter: date_filter,
                    category_filter: category_filter,
                    amount_filter: amount_filter
                },
                success: function(response) {
                    console.log(response); // Check the response in the browser console

                    $('#show-expense').html(response);
                }
            });
        }
    </script>
@endsection
