@extends('layouts.app')
@section('title', 'Cdr 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>
    .audiojs .scrubber { 
display: none; 
} 
</style>
<style>
    /* Custom style for pagination links */
    .pagination {
  
        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;
    }
  
   
    .table > tbody > tr > td, .table > tbody > tr > th {
     padding: 0.5rem; 
    vertical-align: middle;
}

  
</style>
<?php

error_reporting(0);
$startDate = request()->input('start_date') ?? '';
$endDate = request()->input('end_date') ?? '';
$url_page = explode('?',str_replace('/','',$_SERVER['REQUEST_URI']));
$url = $url_page[0];
?>

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

          @php
    $paginator = null;

    if (!empty($report)) {
        $currentPage = $page == 1 ? 1 : (isset($_GET['page']) ? (int) $_GET['page'] : 1);
        $perPage = $show;
        $paginator = new Illuminate\Pagination\LengthAwarePaginator(
            $report,
            $record_count,
            $perPage,
            $currentPage,
            ['path' => url($url)]
        );

        $lower_limit = ($currentPage - 1) * $perPage;
    }
@endphp


        <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>Rvm Cdr 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">
                          @csrf
                        <div class="row">
                   
                        <input type="hidden" class="form-control" name="show" value="10" id="show_value" required="">

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

                                    <input class="form-control " value="{{request()->input('phone_number')}}" name="phone_number" id="phone_number" placeholder="Phone Number">
                                    <!-- <input class="form-control" data-inputmask="'mask':[ '(999) 999-9999']" data-mask  value="{{request()->input('phone_number')}}" name="phone_number" id="phone_number" placeholder="Phone Number"> -->

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

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

                                </div>
                            </div>
                   
                            <div class="form-group col-md-3">
                              <label class="form-label">Status</label>
                              <div class="input-group">
                              <input class="form-control " value="{{request()->input('status')}}" name="status" id="status" placeholder="status">
                            
                                   </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" id="form_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>
<hr class="my-15">
<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="callButton(this.value)">
                            <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>  
                        <div class="table-responsive">
                        <table id="tickets11" class="table mt-0 table-hover no-wrap" data-page-size="10">
                            <thead>
                            <tr>
                                                        <th>#</th>    
                                                        <th>Client Name</th>                                                                                                            
                                                        <th>Campaign</th>
                                                        <th>CLI</th>                                                                       
                                                        <th>Phone</th>
                                                        <th>Sip Trunk Name</th>
                                                        <th>Sip Trunk Provider</th>
                                                        <th>Rvm Domain</th>
                                                        <th>Sip Gateway </th>
                                                        <th>Voicemail Drop Log</th>
                                                        <th>Api Type</th>
                                                        <th>Created at</th>
                                                        <th>Timezone status</th>
                                                        <th>Status</th>
                                                        <th>Tries</th>
               



                                    </tr>
                            </thead>
                            <tbody>
                         
                            @foreach ($paginator as $key=>$value)
                                                        <tr>
                                                            <th scope="row">{{ $paginator->firstItem() + $key }}</th>    
                                                            <td>{{$value->api_client_name}}</td>                                                        
                                                            <td><?php
                                                                if (!empty($value->campaign_id)) {
                                                                    foreach ($campaign_list as $key => $campaign) {
                                                                        if ($campaign->id == $value->campaign_id) {
                                                                            ?>
                                                                            <?php
                                                                            if (!empty($campaign->title)) {
                                                                                echo $campaign->title;
                                                                            }
                                                                            ?>
                                                                            <?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 "";
                                                                }
                                                                ?>
                                                                                                                   
                                                         
                                                                <td style="white-space: nowrap;">                     <?php
                                        // Assuming $fax->callerid contains the caller ID
                                        $callerID = $value->phone;

                                        // 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 "Invalid caller ID";
                                        }
                                        ?></td>
                                                                <td>{{$value->sip_trunk_name}} </td>
                                                                <td>{{$value->sip_trunk_provider}}</td>
                                                                <td>{{$value->rvm_domain_id}}</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';
                                                                }
                                                                ?>
                                                            </td>
                                                            <td>{{$value->voicemail_drop_log_id}}</td>
                                                            <td>{{$value->api_type}}</td>
                                                            <td> {{ \Carbon\Carbon::parse($value->created_at)->format('dS M Y')}}</td>

                                                            <td>{{ $value->timezone_status == 1 ? 'Active' : 'Inactive' }}</td>
                                                            <td>{{$value->status}}</td>
                                                            <td>{{$value->tries}}</td>

                                                        </tr>
                                          @endforeach
                            </tbody>
                         
                        </table>
                        
                        <div style="float:right;">
    @if (!empty($paginator))

    {{ $paginator->appends(request()->except('page'))->links() }}
    @endif

    </div>
                        </div>
                </div>
   

            </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('phone_number');
    var phoneMask = new IMask(phoneInput, {
        mask: '(000) 000-0000'
    }); 
    </script>
 
 <script>
    var phoneInput = document.getElementById('cli');
    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>
<script>
    function callButton(value)
    {
        $("#show_value").val(value);
        $('#form_submit').trigger('click'); 
    }
</script>
@endpush

@endsection



