@extends('layouts.app')
@section('title', 'Api log')
@section('content')

<?php error_reporting(0); ?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
    /* Custom style for pagination links */
    .pagination {
        margin: 0; /* Remove default margin */
        padding: 0; /* Remove default padding */
        list-style: none; /* Remove list bullet points */
        display: flex; /* Use flex layout for horizontal alignment */
    }

    .pagination li a {
        padding:6px;
    }

    .pagination a {
        display: inline-block;
        padding: 0; /* Adjust the padding as needed */
        text-decoration: none;
        background-color: #f0f0f0;
        border: 1px solid #ccc;
        color: #333;
        transition: background-color 0.3s ease, color 0.3s ease;
    }

    .pagination a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .pagination .active a {
        background-color: #007bff;
        color: #fff;
    }
</style>

<style>
    .audiojs .scrubber { 
display: none; 
} 
</style>
<!-- <?php

error_reporting(0);
$startDate = request()->input('start_date') ?? '';
$endDate = request()->input('end_date') ?? '';

?> -->
<?php
    // if (!empty(request()->input('start_date')))
    // {
    //     $startDate = request()->input('start_date');
    // }
    // else
    // {
    //     $current_date = date("Y-m-d"); 
    //     $str_date = strtotime(date("Y-m-d", strtotime($current_date)) . " -15 day");
    //     $startDate = date('Y-m-d', $str_date);
    // }

    // if (!empty(request()->input('end_date')))
    // {
    //     $endDate = request()->input('end_date');
    // }
    // else
    // {
    //     $endDate = date('Y-m-d');
    //}

    $url_page = explode('?',str_replace('/','',$_SERVER['REQUEST_URI']));
    $url = $url_page[0];
?>

    <section class="content">
	
		  <!-- /.row -->

	

        <div class="row">

   
        
        <div class="col-lg-12 col-12">
            <div class="box">
            
               <div class="box-body">  
               <h4 class="box-title text-info mb-0"><i class="fa fa-edit me-15"></i>Api log</h4>
               <a  style="margin-right:5px;float:right;"class="waves-effect waves-light btn btn-rounded btn-primary btn-bitbucket btn-sm" aria-controls="answer-1" aria-expanded="false" data-bs-toggle="collapse"	href="#answer-1" data-parent="#accordion2">
                <i class="fa fa-search fa-lg" aria-hidden="true"></i> Filter
                </a>
                <div class="panel-group panel-group-simple panel-group-continuous mb-0" id="accordion2"
            aria-multiselectable="true" role="tablist">
            <!-- Question 1 -->
            <div class="panel">
              <div id="question-1" role="tab">
             
                      </div>
                      <div class="panel-collapse collapse  " id="answer-1" aria-labelledby="question-1" role="tabpanel" data-bs-parent="#category-1">
                        <div class="panel-body">
                        <form method="post"action="">
                          @csrf
                        <div class="row">
                   

                      
                       
                        
                          
                            <div class="form-group col-md-3">
                              <label class="form-label">Lender Api Type</label>
                              <select id="lender_api_type" name="lender_api_type" class="form-select">
    <option value="">Select</option>
    <option value="ondeck" {{ request()->input('lender_api_type') == 'ondeck' ? 'selected' : '' }}>Ondeck</option>
    <option value="credibly" {{ request()->input('lender_api_type') == 'credibly' ? 'selected' : '' }}>Credibly</option>
    <option value="bitty_advance" {{ request()->input('lender_api_type') == 'bitty_advance' ? 'selected' : '' }}>Bitty Advance</option>
    <option value="fox_partner" {{ request()->input('lender_api_type') == 'fox_partner' ? 'selected' : '' }}>Fox Partner</option>
    <option value="lendini" {{ request()->input('lender_api_type') == 'lendini' ? 'selected' : '' }}>Lendini</option>
    <option value="specialty" {{ request()->input('lender_api_type') == 'specialty' ? 'selected' : '' }}>Specialty</option>
    <option value="forward_financing" {{ request()->input('lender_api_type') == 'forward_financing' ? 'selected' : '' }}>Forward Financing</option>
    <option value="cancapital" {{ request()->input('lender_api_type') == 'cancapital' ? 'selected' : '' }}>CanCapital</option>
</select>

                            </div>
                      
                            <div class="form-group col-md-3">
                              <label class="form-label">Business Id</label>
                                <div class="input-group">
                                                             <span class="input-group-text @error('businessID') text-danger border-danger @enderror"><i class="ti-user"></i></span>

                                    <input class="form-control " value="{{request()->input('businessID')}}" name="businessID" id="businessID">

                                </div>
                            </div>
                   
                  
                           
                            
                            <div class="form-group col-md-3">
                            
                            <label class="form-label">Date Range</label>
                            <div class="input-group">
                            <div class="input-group-addon">
                          <i class="fa fa-calendar"></i>
                      </div>
                      <input type="text" class="form-control pull-right" id="reservation">
                      <input type="hidden" id="start_date" name="start_date" value="{{ $startDate }}">
                      <input type="hidden" id="end_date" name="end_date" value="{{ $endDate }}">                              
                      </div>
                          </div>
                            <div class="box-footer text-end">
        

                <a onclick="window.location.reload();"  class="btn btn-danger me-1">
                  <i class="ti-reload"></i> Reset
                </a>

                <button  type="submit" name="submit" value="add" class="btn btn-primary">
                  <i class="ti-save-alt"></i> Submit
                </button>
              </div>    
  </form>
                          </div>
                        </div>
                      </div>
                    </div>
                  <!-- End Question 1 -->										
                </div>
                <?php
     if (!empty($report)) {
        // Ensure lower_limit is correctly calculated
        if ($lower_limit == '0') {
            $lower_limit = 0;
        }
    
        // Calculate the current page
        $currentPage = isset($_GET['page']) ? (int) $_GET['page'] : 1;
    
        // Define the number of items per page
        $perPage = $show ?? 10; // Use $show if it's defined, default to 10
    
        // Use LengthAwarePaginator to handle pagination
        $paginator = new Illuminate\Pagination\LengthAwarePaginator(
            $report,           // Data to paginate
            $record_count,     // Total record count
            $perPage,          // Items per page
            $currentPage,      // Current page
            ['path' => url($url)] // Base URL for pagination links
        );
        $record_count = $paginator->total();
    
        ?>
              <b>Total Rows :<?= $record_count ?></b>
              <form method="GET" action="">
               
               <label class="label-class" for="show">Show:</label>
                   <select class="form-select-sm"name="show" onchange="this.form.submit()">
                       <option value="10" {{ request('show') == 10 ? 'selected' : '' }}selected>10</option>
                       <option value="25" {{ request('show') == 25 ? 'selected' : '' }}>25</option>
                       <option value="50" {{ request('show') == 50 ? 'selected' : '' }}>50</option>
                       <option value="100" {{ request('show') == 100 ? 'selected' : '' }}>100</option>
                   </select>
                   <label for="entries">entries</label>
                  
               </form>
<hr class="my-15">
                        <div class="table-responsive">
                        <table id="tickets1" class="table mt-0 table-hover no-wrap" data-page-size="10">
                            <thead>
                            <tr>
                                                        <th>#</th>                                                        
                                                        <th>Client</th>
                                                        <th>End Point</th>                                                                       
                                                        <th>Lender</th>
                                                        <!-- <th>Request Data</th> -->
                                                        <th>Response data</th>
                                                        <th>Status Code</th>
                                                        <th>Request Ip </th>
                                                        <th>User Agent</th>
                                                        <th>Business Id</th>
                                                        <th>Lead Id</th>
                                                        <th>Lender Api Type</th>
                                                        <th>Created at</th>
                                    </tr>
                            </thead>
                            <tbody>
                         
                            @foreach ($report as $key=>$value)
                                                        <tr>
                                                            <th scope="row">{{ ($paginator->currentPage() - 1) * $paginator->perPage() + $key + 1 }}</th>                                                            
                                                            <td>
                                                                 <?php
                                                                if (!empty($value->client_id)) {
                                                                    foreach ($clients as $key => $client) {
                                                                        if ($client->id == $value->client_id) {
                                                                            ?>
                                                                            <?php
                                                                            if (!empty($client->company_name)) {
                                                                                echo $client->company_name;
                                                                            }
                                                                            ?>
                                                                            <?php
                                                                        }
                                                                    }
                                                                } else {
                                                                    echo 'N/A';
                                                                }
                                                                ?> 
                                                            </td>
                                                            <td style="white-space: nowrap;">
                                                                <!-- <?php
                                                                // Assuming $fax->callerid contains the caller ID
                                                                $callerID = $value->cli;

                                                                // Remove any non-digit characters from the caller ID
                                                                $callerID = preg_replace('/[^0-9]/', '', $callerID);

                                                                // Check if the caller ID is at least 10 digits long
                                                                if (strlen($callerID) >= 10) {
                                                                    // Extract the last 10 digits
                                                                    $lastTenDigits = substr($callerID, -10);

                                                                    // Format the last 10 digits as (999) 999-9999
                                                                    $formattedLastTenDigits = preg_replace('/(\d{3})(\d{3})(\d{4})/', '($1) $2-$3', $lastTenDigits);

                                                                    // Add a "+" sign in front of the original caller ID
                                                                    $formattedCallerID =  substr($callerID, 0, -10) . $formattedLastTenDigits;

                                                                    // Output the formatted caller ID
                                                                    echo $formattedCallerID;
                                                                } else {
                                                                    // Handle cases where the caller ID is too short
                                                                    echo "";
                                                                }
                                                                ?> -->
                                                                {{$value->endpoint}}
                                                                </td>
                                                                                                                   
                                                         
                                                                <td style="white-space: nowrap;">                    
                                                                <?php
                                                                if (!empty($value->lender_id)) {
                                                                    foreach ($lenders as $key => $lender) {
                                                                        if ($lender->id == $value->lender_id) {
                                                                            ?>
                                                                            <?php
                                                                            if (!empty($lender->lender_name)) {
                                                                                echo $lender->lender_name;
                                                                            }
                                                                            ?>
                                                                            <?php
                                                                        }
                                                                    }
                                                                } else {
                                                                    echo 'N/A';
                                                                }
                                                                ?>       
                                        </td>
                                                                <!-- <td>{{$value->request_data}} </td> -->
                                                                <td>{{$value->response_data}}</td>
                                                                <td>{{$value->status_code}}</td>
                                                                <td>
                                                                    <!-- <?php
                                                                if (!empty($value->sip_gateway_id)) {
                                                                    foreach ($sip_gateways as $key => $gateways) {
                                                                        if ($gateways->id == $value->sip_gateway_id) {
                                                                            ?>
                                                                            <?php
                                                                            if (!empty($gateways->client_name)) {
                                                                                echo $gateways->client_name;
                                                                            }
                                                                            ?>
                                                                            <?php
                                                                        }
                                                                    }
                                                                } else {
                                                                    echo 'N/A';
                                                                }
                                                                ?> -->
                                                                {{$value->request_ip}}
                                                            </td>
                                                            <td>{{$value->user_agent}}</td>
                                                            <td>{{$value->businessID}}</td>
                                                            
                                                            <td>{{ $value-lead_id }}</td>
                                                            <td>{{$value->lender_api_type}}</td>
                                                            <td> {{ \Carbon\Carbon::parse($value->created_at)->format('dS M Y')}}</td>

                                                        </tr>
                                          @endforeach
                </tbody>

              
                         
                        </table>
                        
                      
                        </div>
                        <br>
                       <div style="float:right;"> {{$paginator->appends(Request::all())->links()}}</div>

                       <div>
    Showing 
    {{ ($paginator->currentpage()-1) * $paginator->perpage() + 1 }} 
    to 
    {{ min($paginator->currentpage() * $paginator->perpage(), $paginator->total()) }} 
    of 
    {{ $paginator->total() }} entries
</div>
                </div>
                <?php }?>
            </div>
        </div>
     

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


</section>
@push('styles')

<link rel="stylesheet" type="text/css"
    href="{{ asset('assets/plugins/dashboard_date/bootstrap-datepicker.min.css') }}">
    <link rel="stylesheet" type="text/css"
    href="{{ asset('assets/plugins/dashboard_date/bootstrap-datepicker.css') }}">
@endpush
   
@push('scripts')
	<!-- Vendor JS -->
	
    <script src="{{asset('assets/plugins/dashboard_date/moment.min.js') }}"></script>
    <script src="{{asset('assets/plugins/dashboard_date/bootstrap-datepicker.min.js') }}"></script>
    <script src="{{ asset('assets/plugins/dashboard_date/daterangepicker.js') }}"></script>
<script src="https://cdn.jsdelivr.net/npm/imask"></script>
<script>
    var phoneInput = document.getElementById('mobile');
    var phoneMask = new IMask(phoneInput, {
        mask: '(000) 000-0000'
    }); 
    </script>
 





 <script type="text/javascript">
        $(function () {
            var startDate = "{{ $startDate }}";
            var endDate = "{{ $endDate }}";

            // Log the startDate and endDate for debugging purposes
            console.log("Start Date: ", startDate);
            console.log("End Date: ", endDate);

            $('#reservation').daterangepicker({
                locale: { format: 'MM/DD/YYYY' },
                autoUpdateInput: false, // Prevent auto-filling the input field
                opens: 'right'
            }, function (start, end) {
                $('#start_date').val(start.format('MM/DD/YYYY'));
                $('#end_date').val(end.format('MM/DD/YYYY'));
                $('#reservation').val(start.format('MM/DD/YYYY') + ' - ' + end.format('MM/DD/YYYY')); // Update the input field with the selected date range
            });

            // If both start and end dates are provided, set them in the input field
            if (startDate && endDate) {
                $('#reservation').data('daterangepicker').setStartDate(startDate);
                $('#reservation').data('daterangepicker').setEndDate(endDate);
                $('#reservation').val(startDate + ' - ' + endDate);
            } else {
                $('#reservation').val(''); // Ensure the input field is empty initially
            }
        });
    </script>
        <!-- <script>
document.addEventListener('DOMContentLoaded', function () {
    var searchButton = document.querySelector('.btn-bitbucket');
    var collapseElement = new bootstrap.Collapse(document.getElementById('answer-1'), { toggle: false });
    var leadsHeading = document.getElementById('hide');
    var leadsHeadingShow = document.getElementById('show');

    // Function to check the conditions for opening the form
    function shouldOpenForm() {
        // Check the specified conditions
        return (
            {!! json_encode(
                !empty(request()->input('status')) || 
                !empty(request()->input('cli')) ||
                !empty(request()->input('phone_number')) ||
                !empty(request()->input('start_date')) ||
                !empty(request()->input('end_date'))
            ) !!}
        );
    }

    // Check conditions when the page loads
    if (shouldOpenForm()) {
        collapseElement.show();
        leadsHeading.style.display = 'block';
        leadsHeadingShow.style.display = 'none';
    }

    searchButton.addEventListener('click', function (event) {
        event.preventDefault(); // Prevent the default behavior of the anchor link

        var formFields = document.querySelectorAll('#answer-1 input, #answer-1 select, #answer-1 textarea');

        // Check if any field in the form is not empty
        var isAnyFieldNotEmpty = Array.from(formFields).some(function (field) {
            return field.value.trim() !== '';
        });

        if (isAnyFieldNotEmpty || shouldOpenForm()) {
            // If any field is not empty or specified conditions are met, keep the form open
            collapseElement.show();
            leadsHeading.style.display = 'block';
            leadsHeadingShow.style.display = 'none';
        } else {
            // If all fields are empty and conditions are not met, toggle the form visibility
            collapseElement.toggle();
        }
    });

    // Add an event listener for Bootstrap Collapse events
    collapseElement._element.addEventListener('hidden.bs.collapse', function () {
        leadsHeading.style.display = 'none'; // Hide the heading when the form is collapsed
        leadsHeadingShow.style.display = 'block'; // Show the alternate heading when the form is collapsed
    });

    collapseElement._element.addEventListener('shown.bs.collapse', function () {
        leadsHeading.style.display = 'block'; // Show the heading when the form is expanded
        leadsHeadingShow.style.display = 'none'; // Hide the alternate heading when the form is expanded
    });
});
</script> -->
@endpush

@endsection



