@extends('layouts.app')

@section('title', __('M-Pesa Payments'))

@section('content')
<!-- Content Header (Page header) -->
<section class="content-header">
    <h1>@lang('M-Pesa Payments')</h1>
</section>

<!-- Main content -->
<section class="content">
    <!-- Include DataTables CSS and JS -->
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.6.2/css/buttons.dataTables.min.css">
    <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.js"></script>
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/1.6.2/js/dataTables.buttons.min.js"></script>
    <script type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.html5.min.js"></script>
    <!-- Date Range Picker CSS and JS -->
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />
    <script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>

    <div class="row">
        <div class="col-md-12">
            <div class="box">
                <div class="box-header with-border">
                    <h3 class="box-title">@lang('Filter Payments')</h3>
                </div>
                <div class="box-body">
                    <div class="form-inline">
                        <label for="daterange">@lang('Date Range'):</label>
                        <input type="text" id="daterange" name="daterange" class="form-control" />
                    </div>
                    <br>
                    <table id="mpesa_data" class="display" style="width:100%">
                        <thead>
                            <tr>
                                <th>@lang('#')</th>
                                <th>@lang('Name')</th>
                                <th>@lang('M-Pesa Code')</th>
                                <th>@lang('Amount')</th>
                                <th>@lang('Date')</th>
                                <th>@lang('Status')</th>
                                <th>@lang('Action')</th>
                            </tr>
                        </thead>
                        <tfoot>
                            <tr>
                                <th colspan="4" style="text-align:right">@lang('Total'):</th>
                                <th></th>
                                <th></th>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script>
        $(document).ready(function() {
            var start_date, end_date;

            // Initialize the date range picker
            $('#daterange').daterangepicker({
                opens: 'left',
                autoUpdateInput: false,
                showCustomRangeLabel: true,  // Show the "Custom Range" option
                alwaysShowCalendars: false,  // Hide the calendar until "Custom Range" is selected
                startDate: moment().startOf('month'),
                endDate: moment().endOf('month'),
                locale: {
                    cancelLabel: 'Clear',
                    format: 'MM/DD/YYYY'
                },
                ranges: {
                    'Today': [moment(), moment()],
                    'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                    'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                    'This Month': [moment().startOf('month'), moment().endOf('month')],
                    'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
                    'This Year': [moment().startOf('year'), moment()],
                    'Last Year': [moment().subtract(1, 'year').startOf('year'), moment().subtract(1, 'year').endOf('year')],
                    'Custom Range': [] // Allows users to pick a custom date range
                }
            }, function(start, end, label) {
                start_date = start.format('YYYY-MM-DD');
                end_date = end.format('YYYY-MM-DD');
                $('#daterange').val(start_date + ' - ' + end_date);
                table.draw();
            });

            // Initialize DataTables
            var table = $('#mpesa_data').DataTable({
                processing: true,
                serverSide: true,
                ajax: {
                    url: '{{ route("mpesa.payments.data") }}',
                    data: function(d) {
                        d.start_date = start_date;
                        d.end_date = end_date;
                    }
                },
                columns: [
                    { 
                        data: null, 
                        searchable: false, 
                        orderable: false,
                        render: function (data, type, row, meta) {
                            return meta.row + meta.settings._iDisplayStart + 1; // Auto-incremented row number
                        }
                    },
                    { data: 'firstname', name: 'firstname' }, // Searchable and orderable by default
                    { data: 'transid', name: 'transid' }, // Searchable and orderable by default
                    { data: 'transamount', name: 'transamount' }, // Searchable and orderable by default
                    { data: 'created_at', name: 'created_at' }, // Searchable and orderable by default
                    { data: 'status', name: 'status' }, // Searchable and orderable by default
                    { 
                        data: null,
                        searchable: false, // Disable searching for the action button column
                        orderable: false, // Disable ordering for the action button column
                        render: function (data, type, row) {
                            return `<button class="btn btn-sm btn-success change-status" data-id="${row.id}" ${row.status == 'processed' ? 'disabled' : ''}>${row.status == 'processed' ? 'Processed' : 'Mark as Processed'}</button>`;
                        }
                    }
                ],
                order: [[4, 'desc']], // Order by created_at (column index 4)
                lengthMenu: [[20, 50, 100, 500, -1], [20, 50, 100, 500, "All"]],
                footerCallback: function(row, data, start, end, display) {
                    var api = this.api(), data;
                    var intVal = function (i) {
                        return typeof i === 'string' ? i.replace(/[\$,]/g, '')*1 : typeof i === 'number' ? i : 0;
                    };
                    total = api.column(3).data().reduce(function (a, b) { return intVal(a) + intVal(b); }, 0);
                    $(api.column(3).footer()).html('Total: ' + total);
                }
            });

            
            // Handle the click event for the change status button
            $('#mpesa_data').on('click', '.change-status', function() {
                var recordId = $(this).data('id');
                console.log(recordId);
                $.ajax({
                    url: '{{ route("mpesa.payments.change_status") }}', 
                    method: 'POST',
                    data: {
                        _token: '{{ csrf_token() }}',
                        id: recordId
                    },
                    success: function(response) {
                        if (response.success) {
                            table.ajax.reload(null, false); // Reload table without resetting the pagination
                        } else {
                            alert('Error: ' + response.message);
                        }
                    }
                });
            });

        });
    </script>
</section>
<!-- /.content -->
@endsection
