@extends('template.app')

@section('meta')
@endsection

@section('title')
OBF Approvals
@endsection

@section('styles')
<style>
    .highlight {
        background-color: #ffff99;
    }
    #data-table.dataTable tbody td {
        padding: 0px !important;
        height: 20px !important;
        line-height: 35px !important;
        font-size: 15px !important;
        text-align: center;
    }
    .chart-container {
        margin-top: 30px;
    }
    .chart-card {
        margin-bottom: 20px;
    }
    .form-group .custom_color {
        background-color: lightgrey !important;
    }
</style>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
@endsection

@section('content')
<!-- Flatpickr CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.7/css/jquery.dataTables.min.css">
<style>
    #data-table th, td { 
        white-space: nowrap;
        padding-bottom: 0.50rem !important;
    }
    /*.width_150 {*/
    /*    width: 150px;*/
    /*}*/
    /*.width_200 {*/
    /*    width: 200px;*/
    /*}*/
    /*.width_250 {*/
    /*    width: 250px;*/
    /*}*/
    /*.width_300 {*/
    /*    width: 300px;*/
    /*}*/
   

</style>
<div class="page-breadcrumb">
    <div class="row">
        <div class="col-7 align-self-center">
            <h4 class="page-title text-truncate text-dark font-weight-medium mb-1">OBF Approval</h4>
            <div class="d-flex align-items-center">
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb m-0 p-0">
                        <li class="breadcrumb-item"><a href="{{ route('dashboard') }}" class="text-muted">Dashboard</a></li>
                        <li class="breadcrumb-item"><a href="{{ route('obf_approval') }}" class="text-muted">OBF Approval</a></li>
                        <li class="breadcrumb-item text-muted active" aria-current="page">List</li>
                    </ol>
                </nav>
            </div>
        </div>
    </div>
</div>
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card" style="display: block;">
                <div class="card-body">
                    <table class="table table-bordered data-table" id="data-table" style="text-align: center;">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Date</th>
                                <th>Location</th>
                                <th>Customer Name</th>
                                <th>GST No </th>
                                <th>Team Leader </th>
                                <th>KEC Name </th>
                                <th>Model</th>
                                <th>Variant</th>
                                <th>Exterior Color</th>
                                <th>VIN Number</th>
                                <th width="100">On Road Price(A)</th>
                                <th>Booking Amount (B(+))</th>
                                <th>DP Amount Received (C(+))</th>
                                <th>Finance Amount (D(+)) </th>
                                <th>Exchange Amount (E(+))</th>
                                <th>Total received amount (B+C+D+E = F)</th>
                                <th>Discount (G(-))</th>
                                <th width="100">Net Amount Received (F-G=H)</th>
                                <th width="100">Due Amount (A-H=I)</th>
                                <th>Status</th>
                                <th> OBF Approval Status </th>
                                <th>Action</th>
                            </tr>
                            <tr class="filterrow">
                                <th></th>
                                <th>
                                    <div class="search-box-container datatable-form-filter">
                                        <div class="form-group is-empty">
                                            <input type="text" name="booking_date" value="{{ request()->get('booking_date', '') }}" class="form-control text-capitalize" autocomplete="off" tabindex="1" id="booking_date" placeholder="DD-MM-YYYY to DD-MM-YYYY">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter">
                                        <div class="form-group is-empty">
                                            <input type="text" name="branch_name" value="{{ request()->get('branch_name', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="2">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter">
                                        <div class="form-group is-empty">
                                            <input type="text" name="customer_name" value="{{ request()->get('customer_name', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="3">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter">
                                        <div class="form-group is-empty">
                                            <input type="text" name="gst" value="{{ request()->get('gst', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="4">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter">
                                        <div class="form-group is-empty">
                                            <input type="text" name="team_name" value="{{ request()->get('team_name', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="5">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter">
                                        <div class="form-group is-empty">
                                            <input type="text" name="sales_person_name" value="{{ request()->get('sales_person_name', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="6">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter">
                                        <div class="form-group is-empty">
                                            <input type="text" name="product" value="{{ request()->get('product', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="7">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter">
                                        <div class="form-group is-empty">
                                            <input type="text" name="car_varient_name" value="{{ request()->get('car_varient_name', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="8">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter">
                                        <div class="form-group is-empty">
                                            <input type="text" name="exterior_color" value="{{ request()->get('exterior_color', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="9">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter">
                                        <div class="form-group is-empty">
                                            <input type="text" name="vin_number" value="{{ request()->get('vin_number', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="10">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter">
                                        <div class="form-group is-empty">
                                            <input type="text" name="on_road_price" value="{{ request()->get('on_road_price', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="11">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter">
                                        <div class="form-group is-empty">
                                            <input type="text" name="booking_amount" value="{{ request()->get('booking_amount', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="12">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter">
                                        <div class="form-group is-empty">
                                            <input type="text" name="dp_amount" value="{{ request()->get('dp_amount', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="13">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter">
                                        <div class="form-group is-empty">
                                            <input type="text" name="loan_amount" value="{{ request()->get('loan_amount', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="14">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter">
                                        <div class="form-group is-empty">
                                            <input type="text" name="net_disbusment" value="{{ request()->get('net_disbusment', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="15">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter">
                                        <div class="form-group is-empty">
                                            <input type="text" name="total_exchange_amount" value="{{ request()->get('total_exchange_amount', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="16">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter">
                                        <div class="form-group is-empty">
                                            <input type="text" name="final_total" value="{{ request()->get('final_total', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="17">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter">
                                        <div class="form-group is-empty">
                                            <input type="text" name="finance_discount" value="{{ request()->get('finance_discount', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="18">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter">
                                        <div class="form-group is-empty">
                                            <input type="text" name="net_total" value="{{ request()->get('net_total', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="19">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter">
                                        <div class="form-group is-empty">
                                            <input type="text" name="due_amount" value="{{ request()->get('due_amount', '') }}" class="form-control text-capitalize custom_color" autocomplete="off" autofocus tabindex="20">
                                        </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter">
                                    <div class="form-group">
                                    <select name="status" class="form-control text-capitalize custom_color" tabindex="15">
                                    <option value=""> -- Select Status -- </option>
                                    <option value="pending" {{ request()->get('status') == 'pending' ? 'selected' : '' }}>Pending</option>
                                    <option value="accepted" {{ request()->get('status') == 'accepted' ? 'selected' : '' }}>Accepted</option>
                                    <option value="obf_accepted" {{ request()->get('status') == 'obf_accepted' ? 'obf_accepted' : '' }}>Obf Accepted</option>
                                    <option value="account_accepted" {{ request()->get('status') == 'account_accepted' ? 'account_accepted' : '' }}>Account Accepted</option>
                                    <option value="obf_rejected" {{ request()->get('status') == 'obf_rejected' ? 'obf_rejected' : '' }}>Obf Rejected</option>
                                    <option value="account_rejected" {{ request()->get('status') == 'account_rejected' ? 'account_rejected' : '' }}>Account Rejected</option>
                                    <option value="rejected" {{ request()->get('status') == 'rejected' ? 'rejected' : '' }}>Rejected</option>
                                    <option value="deleted" {{ request()->get('status') == 'deleted' ? 'deleted' : '' }}>Deleted</option>
                                    <option value="completed" {{ request()->get('status') == 'completed' ? 'completed' : '' }}>Completed</option>
                                    <option value="cancel" {{ request()->get('status') == 'cancel' ? 'selected' : '' }}>Cancel</option>
                                    <option value="deal_generated" {{ request()->get('status') == 'deal_generated' ? 'selected' : '' }}>Deal Generated</option>
                                    <option value="delete" {{ request()->get('status') == 'delete' ? 'selected' : '' }}>Delete</option>
                                    <option value="refund_process" {{ request()->get('status') == 'refund_process' ? 'selected' : '' }}>Refund Process</option>
                                    </select>
                                    </div>
                                    </div>
                                </th>
                                <th>
                                    <div class="search-box-container datatable-form-filter">
                                    <div class="form-group">
                                    <select name="approval_status" class="form-control text-capitalize custom_color" tabindex="15">
                                    <option value=""> -- Select Status -- </option>
                                    <option value="pending" {{ request()->get('status') == 'pending' ? 'selected' : '' }}>Pending</option>
                                    <option value="obf_tl_accepted" {{ request()->get('status') == 'obf_tl_accepted' ? 'selected' : '' }}>Obf TL Accepted</option>
                                    <option value="obf_tl_rejected" {{ request()->get('status') == 'obf_tl_rejected' ? 'obf_tl_rejected' : '' }}>Obf TL Rejected</option>
                                    <option value="obf_sm_accepted" {{ request()->get('status') == 'obf_sm_accepted' ? 'obf_sm_accepted' : '' }}>Obf SM Accepted</option>
                                    <option value="obf_gm_accepted" {{ request()->get('status') == 'obf_gm_accepted' ? 'obf_gm_accepted' : '' }}>Obf GM Accepted</option>
                                    <option value="obf_gm_rejected" {{ request()->get('status') == 'obf_gm_rejected' ? 'obf_gm_rejected' : '' }}>Obf GM Rejected</option>
                                    <option value="obf_accountant_accepted" {{ request()->get('status') == 'obf_accountant_accepted' ? 'obf_accountant_accepted' : '' }}>Obf Accountant Accepted</option>
                                    <option value="obf_accountant_rejected" {{ request()->get('status') == 'obf_accountant_rejected' ? 'obf_accountant_rejected' : '' }}>Obf Accountant Rejected</option>
                                    <option value="delete" {{ request()->get('status') == 'delete' ? 'selected' : '' }}>Delete</option>
                                    </select>
                                    </div>
                                    </div>
                                </th>
                                <th></th>
                            </tr>
                        </thead>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>


<div id="DescModal" class="modal fade" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document"> <!-- Small modal size -->
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Enter Remark</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close">&times;</button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="id">
                <input type="hidden" id="status">
                <input type="hidden" id="remark">
                <div class="form-group">
                    <label for="reason"><strong>Reason Remark:</strong></label>
                    <textarea id="reason" class="form-control" rows="3" placeholder="Enter remark..." required></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-primary btn-sm pull-right" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-outline-primary btn-sm pull-right" onclick="status_route()">Submit</button>
            </div>
        </div>
    </div>
</div>

@endsection

@section('scripts')
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script type="text/javascript">
    
    $('#DescModal').on('hidden.bs.modal', function () {
        $(this).attr('inert', 'true');
        $('#id, #status, #reason').val('');
    });
    
    $('#DescModal').on('shown.bs.modal', function () {
        $(this).removeAttr('inert'); 
        $('#reason').focus(); 
    });
    
    window.change_status_reject = function(object) {
        var id = $(object).data("id");
        var status = $(object).data("status");

        $('#DescModal').modal("show");
        $('#id').val(id);
        $('#status').val(status);
        $('#remark').val(status);
    };
    
    window.status_route = function() {
        var remark = $('#remark').val().toLowerCase();
        if (remark.includes('accepted')) {
            window.change_status();
        } else if (remark.includes('rejected')) {
            window.status_reject();
        }
    }   

    window.change_status = function(object) {
        var id = $('#id').val();
        var status = $('#status').val();
        var reason = $('#reason').val().trim();

        if (!reason) {
            toastr.warning('Please enter a reason.', 'Warning'); 
            return;
        }

        $('#DescModal').modal("hide");

        $.ajax({
            url: "{!! route('obf_approval.change.status') !!}",
            type: "POST",
            dataType: "json",
            data: {
                id: id,
                status: status,
                reason: reason,
                _token: "{{ csrf_token() }}"
            },
            success: function(response) {
                if (response.code == 200) {
                    window.LaravelDataTables["dataTableBuilder"].ajax.reload();
                    toastr.success('Status changed successfully', 'Success');
                    // location.reload();
                } else {
                    toastr.error('Failed to change status', 'Error');
                }
            },
            error: function(xhr) {
                toastr.error('An error occurred. Please try again.', 'Error');
            }
        });
    };
    
    window.status_reject = function() {
        var id = $('#id').val();
        var status = $('#status').val();
        var reason = $('#reason').val().trim();

        if (!reason) {
            toastr.warning('Please enter a reason for rejection.', 'Warning');
            return;
        }

        $('#DescModal').modal("hide");

        $.ajax({
            url: "{!! route('obf_approval.change.status') !!}",
            type: "POST",
            dataType: "json",
            data: {
                id: id,
                status: status,
                reason: reason,
                _token: "{{ csrf_token() }}"
            },
            success: function(response) {
                if (response.code == 200) {
                    window.LaravelDataTables["dataTableBuilder"].ajax.reload();
                    window.location.reload();
                    toastr.success('Status changed successfully', 'Success');
                } else {
                    toastr.error('Failed to change status', 'Error');
                }
            },
            error: function(xhr) {
                toastr.error('An error occurred. Please try again.', 'Error');
            }
        });
    };
</script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
<script src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />
<script src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>


<script type="text/javascript">
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
</script>
<script type="text/javascript">
    
    $(document).ready(function() {
        $('#booking_date').daterangepicker({
            autoUpdateInput: false,
            locale: {
                format: 'DD-MM-YYYY',
                cancelLabel: 'Clear'
            }
        });
    
        $('#booking_date').on('apply.daterangepicker', function(ev, picker) {
            $(this).val(picker.startDate.format('DD-MM-YYYY') + ' to ' + picker.endDate.format('DD-MM-YYYY'));
            $('#data-table').DataTable().draw();
        });
    
        $('#booking_date').on('cancel.daterangepicker', function(ev, picker) {
            $(this).val('');
            $('#data-table').DataTable().draw();
        });
        
        let rowCount = $("table tbody tr").length;

        $('.js-example-basic-single').select2();

        var tableColumns = [
            {data: 'id', name: 'id',class:'text-center id',title: 'No.', orderable: false, width:100,default: true},
            {data: 'booking_date', name: 'booking_date',class:'text-center booking_date',title: 'Date', orderable: false,default: true},
            {data: 'branch_name', name: 'branch_name',class:'text-center branch_name',title: 'Location', orderable: false,default: true},
            {data: 'customer_name', name: 'customer_name',class:'text-center customer_name',title: 'Customer Name', orderable: false,default: true},
            {data: 'gst', name: 'gst',class:'text-center gst',title: 'GST No.', orderable: false,default: true},
            {data: 'team_name', name: 'team_name',class:'text-center team_name',title: 'Team Leader', orderable: false,default: true},
            {data: 'sales_person_name', name: 'sales_person_name',class:'text-center sales_person_name',title: 'KEC Name', orderable: false,default: true},
            {data: 'product', name: 'product',class:'text-center product',title: 'Model', orderable: false,default: true},
            {data: 'car_varient_name', name: 'car_varient_name',class:'text-center car_varient_name',title: 'Variant', orderable: false,default: true},
            {data: 'exterior_color', name: 'exterior_color',class:'text-center exterior_color',title: 'Exterior Color', orderable: false,default: true},
            {data: 'vin_number', name: 'vin_number',class:'text-center vin_number',title: 'VIN No.', orderable: false,default: true},
            {data: 'on_road_price', name: 'on_road_price',class:'text-center on_road_price',title: 'On Road Price (A)', orderable: false,default: true},
            {data: 'booking_amount', name: 'booking_amount',class:'text-center booking_amount',title: 'Booking Amount (B(+))', orderable: false,default: true},
            {data: 'dp_amount', name: 'dp_amount',class:'text-center dp_amount',title: 'DP Amount Received (C(+))', orderable: false,default: true},
            {data: 'loan_amount', name: 'loan_amount',class:'text-center loan_amount',title: 'Finance Amount', orderable: false,default: true},
            {data: 'net_disbusment', name: 'net_disbusment',class:'text-center net_disbusment',title: 'Net Disbusment Amount (D(+))', orderable: false,default: true},
            {data: 'total_exchange_amount', name: 'total_exchange_amount',class:'text-center total_exchange_amount',title: 'Exchange Amount (E(+))', orderable: false,default: true},
            {data: 'final_total', name: 'final_total',class:'text-center final_total',title: 'Total received amount (B+C+D+E = F)', orderable: false,default: true},
            {data: 'finance_discount', name: 'finance_discount',class:'text-center finance_discount',title: 'Discount (G(-))', orderable: false,default: true},
            {data: 'net_total', name: 'net_total',class:'text-center net_total',title: 'Net Amount Received (F-G=H)', orderable: false,default: true},
            {data: 'due_amount', name: 'due_amount',class:'text-center due_amount',title: 'Due Amount  (A-H=I)', orderable: false,default: true},
            {data: 'status', name: 'status',class:'text-center status',title: 'Finance Progress Status', orderable: false,default: true},
            {data: 'approval_status', name: 'approval_status',class:'text-center approval_status',title: 'Sales Progress Status', orderable: false,default: true},
        ];
        tableColumns.push({
            data: 'action',
            name: 'action',
            orderable: false,
            searchable: true,
        });

        (function(window, $) {
            window.LaravelDataTables = window.LaravelDataTables || {};
            window.LaravelDataTables["dataTableBuilder"] = $("#data-table").DataTable({
                processing: true,
                serverSide: true,
                language: {
                    "info": "_START_ - _END_ of _TOTAL_",
                    "lengthMenu": "_MENU_ ",
                    "infoFiltered": ""
                },
                paging: true,
                searching: false,
                bSortCellsTop : true,
                ajax: {
                    url: '{!! route("obf_approval") !!}',
                    data: function (d) {
                        d.booking_date = jQuery(".datatable-form-filter input[name='booking_date']").val();
                        d.branch_name = jQuery(".datatable-form-filter input[name='branch_name']").val();
                        d.customer_name = jQuery(".datatable-form-filter input[name='customer_name']").val();
                        d.gst = jQuery(".datatable-form-filter input[name='gst']").val();
                        d.team_name = jQuery(".datatable-form-filter input[name='team_name']").val();
                        d.sales_person_name = jQuery(".datatable-form-filter input[name='sales_person_name']").val();
                        d.product = jQuery(".datatable-form-filter input[name='product']").val();
                        d.car_varient_name = jQuery(".datatable-form-filter input[name='car_varient_name']").val();
                        d.exterior_color = jQuery(".datatable-form-filter input[name='exterior_color']").val();
                        d.vin_number = jQuery(".datatable-form-filter input[name='vin_number']").val();
                        d.on_road_price = jQuery(".datatable-form-filter input[name='on_road_price']").val();
                        d.booking_amount = jQuery(".datatable-form-filter input[name='booking_amount']").val();
                        d.dp_amount = jQuery(".datatable-form-filter input[name='dp_amount']").val();
                        d.loan_amount = jQuery(".datatable-form-filter input[name='loan_amount']").val();
                        d.net_disbusment = jQuery(".datatable-form-filter input[name='net_disbusment']").val();
                        d.total_exchange_amount = jQuery(".datatable-form-filter input[name='total_exchange_amount']").val();
                        d.final_total = jQuery(".datatable-form-filter input[name='final_total']").val();
                        d.finance_discount = jQuery(".datatable-form-filter input[name='finance_discount']").val();
                        d.net_total = jQuery(".datatable-form-filter input[name='net_total']").val();
                        d.due_amount = jQuery(".datatable-form-filter input[name='due_amount']").val();
                        d.status = jQuery(".datatable-form-filter select[name='status']").val();
                        d.approval_status = jQuery(".datatable-form-filter select[name='approval_status']").val();
                    },
                    error : function(d) {}
                },
                columns: tableColumns,
                lengthMenu: [
                    [25, 50,100, -1 ],['25', '50','100', 'Show all' ]
                ],
                order: [],
                responsive: true,
                    colReorder:{
                    enable: false,
                },
                dom: '<"top"f>rt<"bottom"ipl><"clear">',
                fnInitComplete: function(settings, json) {
                    jQuery('table.table input:checkbox').map(function() {
                        if(jQuery(this).prop("checked") != true){
                            var column = table.column( jQuery(this).attr('data-column') );
                            column.visible(false);
                        }
                    });
                },
                pageLength: 25,
                scrollX: true, // Enables horizontal scrolling
                scrollY: '450px',
            });
        })(window, jQuery);

        $("#min").flatpickr({ onSelect: function () { window.LaravelDataTables["dataTableBuilder"].draw(); }, changeMonth: true, changeYear: true });

        $(document).on("change", "#min", function () {
            window.LaravelDataTables["dataTableBuilder"].draw();
        });

        
        $.ajax({
            url: "{{ route('getObfCounts') }}",
            method: "GET",
            success: function(data) {
                createPieChart(data);
            },
            error: function() {
                console.error("Failed to fetch chart data");
            }
        });
    });

    function createPieChart(data) {
        const ctx = document.getElementById('chartCanvas').getContext('2d');
        new Chart(ctx, {
            type: 'pie',
            data: {
                labels: Object.keys(data),
                datasets: [{
                    label: 'Count',
                    data: Object.values(data),
                    backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF'],
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'top',
                    },
                }
            }
        });
    }

    jQuery('.datatable-form-filter input').on('keyup', function (e) {
        if(jQuery(this).val().length >= 3 || e.keyCode == 13 || !jQuery(this).val()) {
            window.LaravelDataTables["dataTableBuilder"].draw();
            e.preventDefault();
        }
    });

    jQuery('.datatable-form-filter select').on('change', function (e) {
        window.LaravelDataTables["dataTableBuilder"].draw();
        e.preventDefault();
    });

    jQuery('input:checkbox[name="name_sort_asc"],input:checkbox[name="name_sort_desc"]').on('click', function (e) {
        window.LaravelDataTables["dataTableBuilder"].draw();
        e.preventDefault();
    });
</script>
@endsection

