@include('staff/header')

            <!-- Page Container START -->

            <div class="page-container">

                <!-- Content Wrapper START -->

                <div class="main-content">    
                <div class="row">
                    <div class="col-lg-12">
                        <div class="horizontal-form">
                            <form action="{{ url('/admin/payout-report-export') }}" method="POST" enctype="multipart/form-data">
                                @csrf
                                <div class="form-group row">
                                    <!--<div class="col-md-6 mb-6">-->
                                    <!--    <input id="date" type="date" class="form-control" name="txndate" value="">-->
                                    <!--</div>-->
                                    
                                    <div class="col-md-2 mb-2">
                                     <label for="fromDate">From</label>
                                      <input id="fromDate" type="date" class="form-control" name="fromDate" value="">
                                      </div>


                                    <div class="col-md-2 mb-2">
                                    <label for="toDate">To</label>
                                    <input id="toDate" type="date" class="form-control" name="toDate" value="">
                                    </div>


                                    <div class="col-md-2 mb-2">
                                    <label for="dropdown">Select Option</label>
                                    <select id="statusdropdown" class="form-control" name="statusdropdown">
                                    <option value="">Status</option>
                                    <option value="PENDING">Pending</option>
                                    <option value="SUCCESS">Success</option>
                                    <option value="FAILED">Failed</option>
                                    </select>
                                     </div>

                                    <div class="col-md-6  mb-6">
                                       <div class="form-group text-left" style="margin-top: 24px;">

                                            
                                            <button type="submit" class="btn btn-md btn-primary">Export</button>
                                            
                                             <button type="button" id="viewButton" class="btn btn-md btn-info">View</button>
                                             
                                        </div> 
                                        
                                   
                                    </div>
                                </div>
                            </form>
                            
                        </div>
                    </div>
                </div>                

                    <div class="row">

                        <div class="col-md-12 col-lg-12">

                            <div class="card">

                                <div class="card-body">

                                    <div class="d-flex justify-content-between align-items-center">

                                        <h5>Payout Transactions</h5>                                        

                                    </div>

                                    <div class="m-t-30">

                                        <div class="table-responsive-md table-responsive-sm table-responsive">

                                            <table class="table table-hover table-bordered" id="datatable"> 

                                                <thead>

                                                    <tr>

                                                        <th>OrderId</th>

                                                        <th>User</th>

                                                        <th>Transaction Id</th>

                                                        <th>UTR</th>

                                                        <th>Name</th>

                                                        <th>A/C No</th>  

                                                        <th>Ifsc</th> 

                                                        <th>Amount</th>                                                        

                                                        <th>Charge</th>

                                                        <th>Gst</th>

                                                        <th>Net Amount</th>

                                                        <th>Status</th>
                                                        
                                                       
                                                        
                                                        <th>CheckStatus</th>

                                                        <th>Date</th>
                                                        
                                                         <th>Remark</th>
                                                         
                                                          <th> IP </th>

                                                    </tr>

                                                </thead>

                                                <tbody>

                                                    

                                                </tbody>

                                            </table>

                                            

                                        </div>

                                        {{-- {{$usertransaction->links()}} --}}

                                    </div>

                                </div>

                            </div>

                        </div>

                       

                    </div>

                </div>

                <!-- Content Wrapper END -->

                <!-- model -->          

                

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>

<link href="https://cdn.datatables.net/v/dt/dt-1.13.5/datatables.min.css" rel="stylesheet">

<script src="https://cdn.datatables.net/v/dt/dt-1.13.5/datatables.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

<script type="text/javascript">

    $(document).ready(function () {



        var url = "{{ route('/admin/payout-report-data') }}";

        let dataTable = new DataTable('#datatable', {



            // ajax: {
            //     url: url,
            //     type: 'POST',
            //     data:{"type":"payout",_token: '{{ csrf_token() }}'},

            // },
             
              ajax: {
                url: url,
                type: 'POST',
                data: function(d) {
                d.type = "payout";
                d.fromDate = $('#fromDate').val();   // Get the value from the 
                d.toDate = $('#toDate').val();       // Get the value from the 
                d.statusdropdown = $('#statusdropdown').val(); // Get the value from the
                d._token = '{{ csrf_token() }}';
            
            },},
            
           
            
            
            processing: true,

            serverSide: true,

            ordering: false,

           

            columns : [

                { "data": "orderId"},

                { "data": "name"},

                { "data": "txnId" },

                { "data": "utr" },

                { "data": "beneName" },

                { "data": "beneAccount" },

                { "data": "beneIfsc" },                 

                { "data": "amount" },

                { "data": "charge" },

                { "data": "gst" },

                { "data": "totalAmount" },

                { 

                    data: 'status',

                    render: function(data, type, row) {

                        if (data === 'SUCCESS') {

                            return ' <button class="btn btn-sm btn-success">'+data+'</button>';

                        } else if (data === 'FAILED') {

                            return ' <button class="btn btn-sm btn-danger">'+data+'</i></button>';

                        } else {

                            return '<button class="btn btn-sm btn-danger">'+data+'</i></button>';

                        }

                    }

                },
                

                
                {
                    "data": "status",
                    "render": function (data, type, row) {
                        if (data === 'PENDING') {
                            return '<button class="btn btn-sm btn-primary check-status-btn" data-orderid="'+ row.orderId +'">Check Status</button>';
                        }
                        return '';
                    }
                },
        

                // { "data": "created_at" ,
                //     render: function(data, type, row) {
                //         return moment(data).format('DD-MM-YYYY  HH:MM:ss');
                //     }
                // },
                 { 
    data: 'created_at',
    render: function(data) {
        // Convert to local timezone
        let date = new Date(data);
        return date.toLocaleString('en-IN', { timeZone: 'Asia/Kolkata', hour12: false });
    }
},
                

          {
                "data": 13,
                render: function (data, type, row) {
                    // Check status first, only apply logic for SUCCESS or FAILED
                    if (row.status === 'SUCCESS' || row.status === 'FAILED') {
                        let createdAt = moment(row.created_at);
                        let updatedAt = moment(row.updated_at);

                        let diffInMinutes = updatedAt.diff(createdAt, 'minutes');
                        
                    //   console.log('Order ID:', row.orderId, ' | Time Difference (minutes):', diffInMinutes);

                        if (diffInMinutes <= 1) {
                            return '<span class="badge badge-success">Instant</span>';
                        } else {
                            return '<span class="badge badge-warning">Delay</span>';
                        }
                    }
                    return '';
                }
            },
            
             { "data": "IpAddress" }
        ],
            
        



            columnDefs: [

            {

                targets: 12, // Index of the column you want to modify

                render: function(data, type, row) {

                    // if (type === 'display' || type === 'filter') {

                        // const dateutc = data.replace('Z', '');
                        // //  console.log(dateutc);
                        // const dt = new Date(`${dateutc}Z`);
                        // const finaldate = moment(dt).format('L, h:mm ss a');

                        // return finaldate ;
                        
                        if (type === 'display' || type === 'filter') {
        
                        return moment(data).format('DD-MM-YYYY  HH:MM:ss');
                    }
                    return data;

                    }

                    

                },
                
                        
        ]    

        });



        // $('#datepicker').on('change', function () {

        //     var newdate = $("#datepicker").val();

        //     $("#datepicker").val(newdate)

        //     //dataTable.draw(); // Redraw the table, which triggers a new AJAX request

        //     dataTable.ajax.reload();

        // });    

 $('#viewButton').on('click', function() {
        dataTable.ajax.reload(); // Redraw the table based on new filters
    });

$('#datatable').on('click', '.check-status-btn', function() {
            var orderId = $(this).data('orderid');
          
           
            $.ajax({
                url: '{{ route("/admin/updatestatus") }}', 
                type: 'POST',
              
                data: {
                    orderId: orderId,
                    _token: '{{ csrf_token() }}'
                },
                success: function(response) {
                    
                  if (typeof response === 'string') {
                try {
                    // Sometimes extra characters are included, let's trim and remove anything after valid JSON
                    let cleanedResponse = response.trim();

                    // Optionally, you can find the last closing brace to ensure valid JSON structure
                    let lastBraceIndex = cleanedResponse.lastIndexOf('}');
                    if (lastBraceIndex !== -1) {
                        cleanedResponse = cleanedResponse.substring(0, lastBraceIndex + 1); // Keep only the JSON part
                    }

                    // Parse the cleaned response
                    response = JSON.parse(cleanedResponse);
                } catch (e) {
                    console.error("Error parsing JSON response:", e);
                    alert('Pending');
                    return;
                }
            }

            // Now check for the status and message
            if (response && response.status && response.message) {
                alert('Status: ' + response.status + '\nMessage: ' + response.message);
            } else {
                console.log("Unexpected response structure: ", response);
                alert('Unexpected response format.');
            }
        },
                error: function(xhr) {
                    alert('Error checking status: ' + xhr.responseText);
                }
            });
        });
    });

</script>



@include('staff/footer')