@extends('layout.app')


@section('css')
    <!-- DataTables -->
    <link rel="stylesheet" href="{{ asset('admin/plugins/datatables-bs4/css/dataTables.bootstrap4.min.css') }}">
@endsection

@section('content')
    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">

            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title" style="color:#115548;">Expense List</h3>
                            <div class="card-tools">

                                {{-- <a href="{{ route('expense-head.index') }}"><button class="btn btn-sm btn-primary"><i
                                            class="fa fa-list" aria-hidden="true"></i> &nbsp;Expense Head List</button></a> --}}

                                <a href="{{ route('expense-head.create') }}"><button class="btn btn-sm btn-primary"><i
                                            class="fa fa-plus-circle" aria-hidden="true"></i> &nbsp; Expense
                                        Type</button></a>


                                <button data-toggle="modal" data-target="#expenseAdd" class="btn btn-sm btn-primary"><i
                                        class="fa fa-plus-circle" aria-hidden="true"></i> &nbsp; Expense</button>

                                @if (checkSettings('expense_approve_multiple') == 'enable')
                                    <button id="approveSelected" class="btn btn-sm btn-primary">Approve</button>
                                @endif
                            </div>
                        </div>
                        <!-- /.card-header -->
                        <div class="card-body">
                            <div class="table-responsive">
                                <table id="dataTable" class="display">
                                    <thead>
                                        <tr>
                                            @if (checkSettings('expense_approve_multiple') == 'enable')
                                                <th>
                                                    <input type="checkbox" id="selectAll">
                                                </th>
                                            @endif
                                            <th>#</th>
                                            <th>Status</th>
                                            {{-- <th>Income Head</th> --}}
                                            <th>Name</th>
                                            <th>Expense Head</th>
                                            <th>Employee</th>
                                            <th>Invoice Number</th>
                                            <th>Date</th>
                                            <th>Amount</th>
                                            <th>Bank Account</th>
                                            <th>Documents</th>
                                            <th>Description</th>
                                            <th>Create By</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {{-- Data will be loaded via AJAX --}}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <!-- /.card-body -->
                    </div>
                    <!-- /.card -->



                    <div class="modal fade" id="expenseAdd" role="dialog" aria-labelledby="exampleModalCenterTitle"
                        aria-hidden="true">
                        <div class="modal-dialog modal-dialog-centered" role="document">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title" id="exampleModalLongTitle">Add Expense</h5>
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                        <span aria-hidden="true">&times;</span>
                                    </button>
                                </div>
                                <form method="POST" action="{{ route('expense.store') }}" enctype="multipart/form-data">
                                    @csrf
                                    <div class="modal-body">


                                        <div class="card-body">

                                            <div class="row">

                                                <div class="col-md-12">
                                                    <label for="shortname">
                                                        Expense Title*
                                                    </label>
                                                    <input type="text" name="name" class="form-control"
                                                        placeholder="Enter Name" required>
                                                </div>

                                                <div class="col-md-12">
                                                    <label for="shortname">
                                                        Expense Head*
                                                    </label>
                                                    <select name="expenseHead" id="expense_head"
                                                        class="form-control select2" required>
                                                        <option value="">Select One</option>
                                                        @foreach ($expenseHead as $item)
                                                            <option value="{{ $item->id }}">{{ $item->name }}
                                                            </option>
                                                        @endforeach
                                                    </select>
                                                </div>

                                                <div class="col-md-12" style="display: none" id="employee_block">
                                                    <label for="employee">Select Employee</label>
                                                    <select name="employee" id="employee" class="form-control">
                                                        <option value="">Select Employee</option>
                                                        @foreach (getEmployesInExpense() as $employee)
                                                            <option value="{{ $employee->id }}">{{ $employee->name }}
                                                            </option>
                                                        @endforeach
                                                    </select>
                                                </div>

                                                <div class="col-md-12" id="invoice">
                                                    <label for="shortname">
                                                        Invoice Number
                                                    </label>
                                                    <input type="text" name="invoice_number" class="form-control"
                                                        placeholder="Enter Invoice Number">
                                                </div>
                                                <div class="col-md-12">

                                                    <label for="shortname">
                                                        Date*
                                                    </label>


                                                    <div class="input-group date" id="searchFrom"
                                                        data-target-input="nearest">
                                                        <input type="text" name="date"
                                                            class="form-control datetimepicker-input input-group-append"
                                                            data-toggle="datetimepicker" data-target="#searchFrom"
                                                            autocomplete="off">
                                                    </div>



                                                    {{--
                                                    <input type="date" name="date" class="form-control "
                                                        placeholder="Enter Date" required> --}}
                                                </div>
                                                {{-- <div class="col-md-12">
                                            <label for="shortname">
                                                Date*
                                            </label>
                                            <div class="input-group date" id="searchTo" data-target-input="nearest">
                                                <input type="text" name="date"
                                                    class="form-control datetimepicker-input input-group-append"
                                                    data-toggle="datetimepicker" data-target="#searchTo" autocomplete="off">
                                            </div>
                                        </div> --}}
                                                <div class="col-md-12">
                                                    <label for="shortname">
                                                        Amount*
                                                    </label>
                                                    <input type="number" name="amount" class="form-control"
                                                        placeholder="Enter Amount" required>
                                                </div>
                                                <div class="col-md-12 mt-2">
                                                    <label for="shortname">Attach Document</label>
                                                    <input type="file" name="attach_document">
                                                </div>
                                                @if (checkSettings('bank_account_withdraw') == 'enable')
                                                <div class="col-md-12 mt-2">
                                                    <div class="form-group">
                                                        <label for="expense_bank_account_id">
                                                            Bank Account (Optional)
                                                        </label>
                                                        <select name="bank_account_id" id="expense_bank_account_id" class="form-control">
                                                            <option value="">Select Bank Account</option>
                                                            @php
                                                                $bankAccounts = \App\Models\Banking::where('status', 1)->get();
                                                            @endphp
                                                            @if($bankAccounts->count() > 0)
                                                                @foreach ($bankAccounts as $bankAccount)
                                                                    <option value="{{ $bankAccount->id }}">{{ $bankAccount->account_name }} -- {{ $bankAccount->bank_name }}</option>
                                                                @endforeach
                                                            @endif
                                                        </select>
                                                        <small class="text-muted">If selected, expense amount will be withdrawn from this account.</small>
                                                    </div>
                                                </div>
                                                @endif
                                                <div class="col-md-12">
                                                    <label for="shortname">
                                                        Description
                                                    </label>
                                                    <textarea name="description" class="form-control" placeholder="Type Description"></textarea>
                                                </div>

                                            </div>
                                        </div>


                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-secondary"
                                            data-dismiss="modal">Close</button>
                                        <button type="submit" class="btn btn-primary">Add Expense</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>


                </div>
            </div>
            <!-- /.row -->

        </div><!-- /.container-fluid -->
    </section>
    <!-- /.content -->
@endsection
@section('ajax')
    <script>
        $(function() {

            $('#expense_head').on('change', function() {
                let type = $('#expense_head').val();
                console.log(type);
                // if (type == 1) {
                $('#employee_block').show();
                // $('#invoice').hide();
                // } else {
                // $("#employee option:selected").prop("selected", false)
                // $('#employee_block').hide();
                $('#invoice').show();
                // }
            });


            // Initialize server-side DataTables
            @php
                $orderColumnIndex = checkSettings('expense_approve_multiple') == 'enable' ? 1 : 0;
            @endphp

            // Destroy existing DataTable instance if it exists
            if ($.fn.DataTable.isDataTable('#dataTable')) {
                $('#dataTable').DataTable().destroy();
            }

            var table = $('#dataTable').DataTable({
                "processing": true,
                "serverSide": true,
                "ajax": {
                    "url": "{{ route('expense.data') }}",
                    "type": "GET",
                    "error": function(xhr, error, code) {
                        console.log('Error:', error, code);
                        alert('Error loading data. Please refresh the page.');
                    }
                },
                "columns": [
                    @if (checkSettings('expense_approve_multiple') == 'enable')
                    {
                        "data": "checkbox",
                        "name": "checkbox",
                        "orderable": false,
                        "searchable": false,
                        "render": function(data, type, row) {
                            return '<input type="checkbox" class="selectRow" data-id="' + row.id + '">';
                        }
                    },
                    @endif
                    { "data": "id", "name": "id" },
                    { "data": "status", "name": "status", "orderable": true, "searchable": false },
                    { "data": "name", "name": "name" },
                    { "data": "expense_head", "name": "expense_head" },
                    { "data": "employee", "name": "employee" },
                    { "data": "invoice_number", "name": "invoice_number" },
                    { "data": "date", "name": "date" },
                    { "data": "amount", "name": "amount" },
                    { "data": "bank_account", "name": "bank_account", "orderable": false, "searchable": false },
                    { "data": "document", "name": "document", "orderable": false, "searchable": false },
                    { "data": "description", "name": "description" },
                    { "data": "created_by", "name": "created_by" },
                    { "data": "action", "name": "action", "orderable": false, "searchable": false }
                ],
                "order": [[{{ $orderColumnIndex }}, "desc"]],
                "pageLength": 25,
                "lengthMenu": [[10, 25, 50, 100], [10, 25, 50, 100]],
                "searchDelay": 500,
                "responsive": true,
                "autoWidth": false
            });


        });

        // Select all checkboxes (using event delegation for dynamically loaded rows)
        $(document).on('change', '#selectAll', function() {
            var isChecked = $(this).prop('checked');
            $('.selectRow').prop('checked', isChecked);
        });

        // Approve all selected expenses
        $('#approveSelected').on('click', function() {
            let selectedIds = [];

            $('.selectRow:checked').each(function() {
                selectedIds.push($(this).data('id'));
            });

            if (selectedIds.length === 0) {
                alert('Please select at least one expense to approve');
                return;
            }

            if (confirm('Are you sure you want to approve all selected expenses?')) {
                // Send AJAX request to approve multiple expenses
                $.ajax({
                    url: "{{ route('expense-approve-multiple') }}",
                    method: 'POST',
                    data: {
                        ids: selectedIds,
                        _token: '{{ csrf_token() }}'
                    },
                    success: function(response) {
                        location.reload();
                    },
                    error: function(xhr) {
                        alert('Error approving expenses');
                    }
                });

            }
        });
    </script>
    <!-- DataTables -->
    {{-- <script src="{{ asset('admin/plugins/datatables/jquery.dataTables.min.js') }}"></script>
    <script src="{{ asset('admin/plugins/datatables-bs4/js/dataTables.bootstrap4.min.js') }}"></script>
    <script src="{{ asset('admin/plugins/datatables-responsive/js/dataTables.responsive.min.js') }}"></script>
    <script src="{{ asset('admin/plugins/datatables-responsive/js/responsive.bootstrap4.min.js') }}"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script> --}}
@endsection
