@extends('layouts.app')
@section('title', 'Report')
@section('content')
<meta name="csrf-token" content="{{ csrf_token() }}">
<?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>

<?php

use \App\Http\Controllers\InheritApiController;
$userdetails = InheritApiController::headerUserDetails();
$startDate = request()->input('start_date') ?? '';
$endDate = request()->input('end_date') ?? '';
    // 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];
?>
<style>
    .audiojs .scrubber { 
display: none; 
} 
</style>


    <section class="content">
			<div class="row">			  
				<div class="col-lg-12 col-12">
					  <div class="box">
						
						<!-- /.box-header -->
                        <form class="needs-validation" action="" method="post">
                            @csrf

                        <input type="hidden" class="form-control" name="show" value="10" id="show_value" required="">

                        <input type="hidden" class="form-control" name="campaign_id" value="{{$campaign_list[0]->id}}" id="campaign_name" required="">
							<div class="box-body">
								<h4 class="box-title text-info mb-0"><i class="fa fa-edit me-15"></i> Call Reports</h4>

								<hr class="my-15">
								<div class="row">
								  <div class="col-md-6">
                                  <div class="form-group">
									<label class="form-label">Phone No</label>
									<div class="input-group mb-3">
										<span class="input-group-text"><i class="ti-user"></i></span>
                                        <input type="text" class="form-control" placeholder="Enter Phone Number" onkeypress="return isNumberKey(event)" type="" name="number" value="{{ request()->input('number') }}" id="mobile" maxlength="" >
									</div>
								</div>
								  </div>
                                  @if(Session::get('level') >= 5)
                                
                                <div class="col-md-6">
									<div class="form-group">
									  <label class="form-label">Extension List</label>
                                        <div class="input-group mb-3">
                                            <span class="input-group-text @error('caller_id') text-danger border-danger @enderror"><i class="ti-user"></i></span>

                                            <select class="form-select" name="extension" id="extension">
                                        <option value="">Select</option>
                                        @foreach($extension_list as $key => $extension)

                                        @if((request()->session()->get('level') > 9))
                                        @if(($extension->user_level <= 9) || ($extension->extension == request()->session()->get('extension')))
                                        <option @if($extension->extension == request()->input('extension'))  selected @endif value="{{$extension->extension}}">{{$extension->first_name}} {{$extension->last_name}} - {{$extension->extension}} @if($extension->is_deleted == 1) (Removed User) @endif</option>
                                        @endif

                                        @elseif(($extension->user_level < 9) || ($extension->extension == request()->session()->get('extension')))
                                        <option @if($extension->extension == request()->input('extension'))  selected @endif value="{{$extension->extension}}">{{$extension->first_name}} {{$extension->last_name}} - {{$extension->extension}} @if($extension->is_deleted == 1) (Removed User) @endif</option>
                                        @endif


                                        @endforeach
                                    </select>								
                                        </div>
								  </div>
								</div>
                                <div class="col-md-6">
                                  <div class="form-group">
									<label class="form-label">Campaign</label>
									<div class="input-group mb-3">
										<span class="input-group-text"><i class="ti-user"></i></span>
                                        <select name="campaign" class="form-select" id="campaign" onchange="getDisposition();">
                                            <option value="">Select</option>
                                            @foreach($campaign_list as $key => $campaign)
                                            @if(!empty($campaign->title) & ($campaign->status==1))
                                            <option @if($campaign->id == request()->input('campaign'))  selected @endif value="{{$campaign->id}}">{{$campaign->title}}</option>
                                            @endif
                                            @endforeach
                                        </select>
                                	</div>
								</div>
                                </div> 
                                @else

                                <div class="col-md-6"  >
                                  <div class="form-group">
									<label class="form-label">Campaign </label>
									<div class="input-group mb-3">
										<span class="input-group-text"><i class="ti-user"></i></span>
                                        <select name="campaign" class="form-select" id="campaign" onchange="getDisposition();">
                                            <option value="">Select</option>
                                            @foreach($campaign_list as $key => $campaign)
                                            @if(!empty($campaign->title))
                                            <option @if($campaign->id == request()->input('campaign'))  selected @endif value="{{$campaign->id}}">{{$campaign->title}}</option>
                                            @endif
                                            @endforeach
                                        </select>
                                	</div>
								</div>
                              </div>
                              @endif
                              <div class="col-md-6">
                                  <div class="form-group">
									<label class="form-label">Disposition</label>
									<div class="input-group mb-3">
                                    <select class="form-select select2 select2-hidden-accessible" multiple="" data-placeholder="Select Disposition" name="disposition[]" style="width: 100%; 
               -webkit-appearance: none; 
               -moz-appearance: none; 
               appearance: none; 
               background: url('data:image/svg+xml;utf8,<svg fill=\'%23333\' height=\'24\' viewBox=\'0 0 24 24\' width=\'24\' xmlns=\'http://www.w3.org/2000/svg\'><path d=\'M7 10l5 5 5-5z\'/></svg>') no-repeat right 10px center; 
               background-size: 16px 16px; 
               padding-right: 30px;">
    <option value="">Select Disposition</option>
    <option @if(in_array(0, (array)request()->input('disposition'))) selected @endif value="0">No Agent</option>
    <option @if(in_array(101, (array)request()->input('disposition'))) selected @endif value="101">No Agent Available</option>
    <option @if(in_array(102, (array)request()->input('disposition'))) selected @endif value="102">AMD Hangup</option>
    <option @if(in_array(103, (array)request()->input('disposition'))) selected @endif value="103">Voice Drop</option>
    <option @if(in_array(104, (array)request()->input('disposition'))) selected @endif value="104">Cancelled By User</option>
    <option @if(in_array(105, (array)request()->input('disposition'))) selected @endif value="105">Channel Unavailable</option>
    <option @if(in_array(106, (array)request()->input('disposition'))) selected @endif value="106">Congestion</option>
    <option @if(in_array(107, (array)request()->input('disposition'))) selected @endif value="107">Line Busy</option>
    @foreach($disposition_list as $disposition)
        <option @if(in_array($disposition->id, (array)request()->input('disposition'))) selected @endif value="{{$disposition->id}}">{{$disposition->title}}</option>
    @endforeach
</select>

                                        <!-- <select name="disposition" class="form-select" id="disposition"  >
                                        <option value="">Select Disposition</option>
                                        <option @if(request()->input('disposition') == '0')   selected @endif  value="0">No Agent</option>
                                        <option @if(request()->input('disposition') == '101')   selected @endif  value="101">No Agent Available</option>
                                        <option @if(request()->input('disposition') == '102')   selected @endif  value="102">AMD Hangup</option>
                                        <option @if(request()->input('disposition') == '103')   selected @endif  value="103">Voice Drop</option>
                                        <option @if(request()->input('disposition') == '104')   selected @endif  value="104">Cancelled By User</option>
                                        <option @if(request()->input('disposition') == '105')   selected @endif  value="105">Channel Unavailable</option>
                                        <option @if(request()->input('disposition') == '106')   selected @endif  value="106">Congestion</option>
                                        <option @if(request()->input('disposition') == '107')   selected @endif  value="107">Line Busy</option>

                                        @foreach($disposition_list as $key => $disposition)
                                        <option @if($disposition->id == request()->input('disposition'))  selected @endif value="{{$disposition->id}}">{{$disposition->title}}</option>
                                        @endforeach



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

                                                <select name="route" class="form-select" id="route"> 


                                                    <option value="">Select</option>
                                                    <option @if(request()->input('route') == 'IN')  selected @endif value="IN">Incoming</option>
                                                    <option @if(request()->input('route') == 'OUT')  selected @endif value="OUT">Outgoing</option>
                                                    <option @if(request()->input('route') == 'TRANSFER')  selected @endif value="TRANSFER">Transfers</option>
                                                </select>
                                                <div class="valid-tooltip"></div>
                                            </div>
                                        </div>
                                    </div>
							
                                    <div class="col-md-6">
                                        <div class="form-group @error('description') has-error @enderror">
                                        <label class="form-label">Type</label> 
                                            <div class="input-group mb-3">
                                                    <span class="input-group-text @error('caller_id') text-danger border-danger @enderror"><i class="ti-user"></i></span>
                                                    <select name="type" class="form-select" id="type" onchange="getDisposition();">
                                            <option value="">Type</option>
                                            <option @if(request()->input('type') == 'dialer')  selected @endif value="dialer">Dialer</option>
                                            <option @if(request()->input('type') == 'c2c')  selected @endif value="c2c">C2C</option>
                                            <option @if(request()->input('type') == 'manual')  selected @endif value="manual">Manual</option>

                                            <option @if(request()->input('type') == 'predictive_dial')  selected @endif value="predictive_dial">Predictive Dial</option>

                                            <option @if(request()->input('type') == 'outbound_ai')  selected @endif value="outbound_ai">Outbound AI</option>

                                        </select>
                                                </div>
                                            </div>
                                    </div>
								
							
                           
                                    @if(Session::get('level') >= 5)
								  <div class="col-md-6">
                                  <div class="form-group"data-select2-id="13">
									<label id="label_id"class="form-label">DID Lists </label>
									<div class="input-group mb-3">
                                        <select class="form-select select2 select2-hidden-accessible" multiple="" data-placeholder="Select a DIDs" data-select2-id="7" tabindex="-1" aria-hidden="true" name="did_numbers[]"     style="width: 100%; 
               -webkit-appearance: none; 
               -moz-appearance: none; 
               appearance: none; 
               background: url('data:image/svg+xml;utf8,<svg fill=\'%23333\' height=\'24\' viewBox=\'0 0 24 24\' width=\'24\' xmlns=\'http://www.w3.org/2000/svg\'><path d=\'M7 10l5 5 5-5z\'/></svg>') no-repeat right 10px center; 
               background-size: 16px 16px; 
               padding-right: 30px;">
                                                        <option value="">Select</option>
                                            @foreach($did_list as $key => $did)
                                                                                    
                                        <option @if (old("did_numbers")){{ (in_array($did->cli, old("did_numbers")) ? "selected":"") }}@endif value="{{$did->cli}}">{{$did->cli}}
                                        @php
                                        $role = Session::get('role');
                                    @endphp

@if(in_array($role, ['system_admin', 'system_administrator']))(<?php echo $did->voip_provider ?>)
                                    @endif
                                        </option>

                                        @endforeach
                                         </select>
                                	</div>
								</div>
                                </div>
                                @endif

                                <div class="col-md-3">
                                  <div class="form-group">
									<label id="label_id_duration" class="form-label">Timezone </label>
									<div class="input-group mb-3">
										<span class="input-group-text"><i class="ti-user"></i></span>
                                        <select name="timezone_value" class="form-select">
                                            <option value="">Select TimeZone</option>
                                            @foreach($timezone_lists as $key => $zone)
                                            <option @if($zone->timezone == request()->input('timezone_value'))  selected @endif value="{{$zone->timezone}}">{{$zone->timezone_name}} ({{$zone->timezone}})</option>
                                            @endforeach
                                        </select>
                                	</div>
								</div>
                            </div>
                          <div class="col-md-3">
                            <div class="form-group">
                                <label class="form-label">Duration</label>
                                <div class="input-group mb-3">
                                    <span class="input-group-text"><i class="ti-bolt"></i></span>
                                    <select name="duration" class="form-select" id="duration">
                                        <option value="">Select</option>

                                        <option value="60" {{ request('duration') == '60' ? 'selected' : '' }}>
                                            1 Min
                                        </option>

                                        <option value="120" {{ request('duration') == '120' ? 'selected' : '' }}>
                                            2 Min
                                        </option>

                                        <option value="300" {{ request('duration') == '300' ? 'selected' : '' }}>
                                            5 Min
                                        </option>

                                        <option value="600" {{ request('duration') == '600' ? 'selected' : '' }}>
                                            10 Min
                                        </option>

                                        <option value="1200" {{ request('duration') == '1200' ? 'selected' : '' }}>
                                            20 Min
                                        </option>

                                        <option value="1800" {{ request('duration') == '1800' ? 'selected' : '' }}>
                                            30 Min
                                        </option>
                                    </select>
                                </div>
                            </div>
                          </div>
                            <div class="col-md-6">
                                  <div class="form-group">
									<label class="form-label">Date range:</label>
									<div class="input-group mb-3">
                                            <div class="input-group-addon">
                                                <i class="fa fa-calendar"></i>
                                            </div>
                                            <input type="text" class="form-control pull-right cdr-range" id="reservation2">
                                            <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>
                       
                           
								 
                                <div class="col-md-6" >
                                  <div class="form-group">
									<label class="form-label">State / City / Area Codes </label>
									<div class="input-group mb-3">
                                        <select name="area_code[]" class="form-select select2 select2-hidden-accessible" multiple="" data-placeholder="Select State / City /Areacode" data-select2-id="8" tabindex="-1" aria-hidden="true"     style="width: 100%; 
               -webkit-appearance: none; 
               -moz-appearance: none; 
               appearance: none; 
               background: url('data:image/svg+xml;utf8,<svg fill=\'%23333\' height=\'24\' viewBox=\'0 0 24 24\' width=\'24\' xmlns=\'http://www.w3.org/2000/svg\'><path d=\'M7 10l5 5 5-5z\'/></svg>') no-repeat right 10px center; 
               background-size: 16px 16px; 
               padding-right: 30px;">
                                            <option value="">Select Area Code</option>
                                            @foreach($area_codes as $key => $area)
                                            <option @if($area->areacode == request()->input('area_code'))  selected @endif value="{{$area->areacode}}">{{$area->state_name}} - {{$area->city_name}} - {{$area->areacode}}</option>
                                            @endforeach
                                        </select>
                                	</div>
								</div>
                            </div>
                    
                                </div>
                               
                            </div>
                        
                          
                      
                          
                           
							<!-- /.box-body -->
							<div class="box-footer text-end"style="margin-right:15px;">
                            <button type="submit" name="submit" id="form_submit"  value="Search" class="btn btn btn-primary waves-effect waves-light"><i class="fa fa-search" aria-hidden="true"></i> Search</button>
                            <button type="submit" name="submit_download" class="btn btn-danger waves-effect waves-light m-l-10" value="1"> <i class="fa fa-file-pdf-o"></i> PDF</button>                                     
                            <button type="submit" name="submit_download" class="btn btn-success waves-effect waves-light m-l-10" value="2"><i class="fa fa-file-excel-o" aria-hidden="true"></i> Excel</button>
							</div>  
						</form>
					  </div>
					  <!-- /.box -->			

                    </div>  

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

	

        <div class="row">

        <?php
        
                    if (!empty($report)) {
                   

                    if($page == 1)
                    {
                        $currentPage = 1;
                    }

                    else
                    {
                        $currentPage = isset($_GET['page']) ? (int) $_GET['page'] : 1;
                    }

                    $perPage = $show;
                    $paginator = new Illuminate\Pagination\LengthAwarePaginator($report, $record_count, $perPage, $currentPage, ['path' => url($url)]);
                ?>
        
        <div class="col-lg-12 col-12">
            <div class="box">
            
               <div class="box-body">  
                    <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  class="table mt-0 table-hover no-wrap" data-page-size="10">
                            <thead>
                            <tr>
                                                        <th>#</th>
                                                        <th>Extension</th>
                                                        <th>Campaign</th>
                                                        <th>CLI</th>                
                                                        <th>Route</th>
                                                        <th>Type</th>
                                                        <th >Number</th>
                                                        <th>Disposition</th>
                                                        <th>Duration</th>
                                                        <th>State/City</th>
                                                        <th>Start Time</th>
                                                        <th>End Time</th>
                                                        <th>Recording</th>
                                                        <th>Action</th>
                                                        @if(Session::get('level') == 11 && $callchex == 1 && $callchex_status == 1)
                                                        <th>Analyze</th>
                                                        @endif


                                    </tr>
                            </thead>
                            <tbody>
                            <?php
                                                    $k = $lower_limit;
                                                    foreach ($paginator->items() as $key => $value) {

                                                                $timezone = $userdetails->data->timezone;
                                                                if(!empty($timezone))
                                                                {
                                                                    if(!empty($value->start_time))
                                                                    {
                                                                    $utc_start_time = $value->start_time;
                                                                    $dt_start_time = new DateTime($utc_start_time);
                                                                    $tz = new DateTimeZone($timezone); // or whatever zone you're after
                                                                    $dt_start_time->setTimezone($tz);
                                                                    $start_time = $dt_start_time->format('Y-m-d H:i:s');

                                                                    }
                                                                    else
                                                                    {
                                                                        $start_time='-';
                                                                    }

                                                                    if(!empty($value->end_time))
                                                                    {

                                                                    $utc_end_time = $value->end_time;
                                                                    $dt_end_time = new DateTime($utc_end_time);
                                                                    $tz = new DateTimeZone($timezone); // or whatever zone you're after
                                                                    $dt_end_time->setTimezone($tz);    
                                                                    $end_time = $dt_end_time->format('Y-m-d H:i:s');
                                                                }
                                                                else
                                                                {
                                                                        $end_time='-';

                                                                }

                                                                }
                                                                else
                                                                {
                                                                    if(!empty($value->start_time))
                                                                    {
                                                                    $start_time = $value->start_time;
                                                                }
                                                                else
                                                                {
                                                                    $start_time='-';
                                                                }

                                                            if(!empty($value->end_time))
                                                                    {
                                                                    $end_time = $value->end_time;
                                                                }
                                                                else
                                                                {
                                                                    $end_time='-';
                                                                }

                                                                }
                                                                
                                                        ?>                          
                                                        <tr>
                                            <th scope="row"><?php echo ++$k; ?></th>
                                            <td> <?php 
                                                            foreach($extension_list as $key => $extension)
                                                            {
                                                                if($extension->extension == $value->extension)
                                                                {
                                                                    $ext_name = $extension->first_name.' '.$extension->last_name.'-'.$value->extension;
                                                                }
                                                                else
                                                                if($extension->alt_extension == $value->extension)
                                                                {
                                                                    $ext_name = $extension->first_name.' '.$extension->last_name.'-'.$value->extension;
                                                                }

                                                                else
                                                                if($value->extension == NULL)
                                                                {
                                                                    $ext_name = 'N/A';
                                                                }
                                                                else
                                                                {
                                                                    $num = $value->extension;
                                                                    $numlength = strlen((string)$num);
                                                                    if($numlength > 9)
                                                                    {
                                                                        $ext_name = $value->extension;
                                                                    }
                                                                }

                                                            }
                                                            echo $ext_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
                                                            if(!empty($value->cli)) {
                                        // 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 "Invalid caller ID";
                                        }
                                    }
                                        else{
                                        echo 'N/A';
                                        } 
                                        ?>
                                    


                                                          </td>
                                                                <td><?php echo $value->route; ?></td>
                                                                <td><?php 
                                                                if($value->type == 'manual')
                                                                    $dial = 'Manual';
                                                                else
                                                                if($value->type == 'dialer')
                                                                    $dial = 'Dialer';
                                                                else
                                                                if($value->type == 'predictive_dial')
                                                                    $dial = 'Predictive';

                                                                else
                                                                if($value->type == 'c2c')
                                                                    $dial = 'C2C';

                                                                else
                                                                if($value->type == 'outbound_ai')
                                                                    $dial = 'Outbound AI';
                                                                echo $dial; ?></td>
                                                                <td style="white-space: nowrap;">
                                                            
                                                                <?php
                                        // Assuming $fax->callerid contains the caller ID
                                        $callerID = $value->number;

                                        // 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><?php
                                                                if (!empty($value->disposition_id)) {
                                                                    // echo "<pre>";print_r($disposition_list);die;
                                                                    foreach ($disposition_list as $key => $dispo) {
                                                                        if ($dispo->id == $value->disposition_id) {
                                                                            ?>
                                                                            <?php echo $dispo->title; ?>
                                                                            <?php
                                                                        }
                                                                    else
                                                                        if($value->disposition_id == '101')
                                                                        {
                                                                            echo "No Agent Available";
                                                                            break;
                                                                        }
                                                                    
                                                                        else
                                                                        if($value->disposition_id == '102')
                                                                        {
                                                                            echo "AMD Hangup";
                                                                            break;
                                                                        }
                                                                    
                                                                        else
                                                                        if($value->disposition_id == '103')
                                                                        {
                                                                            echo "Voice Drop";
                                                                            break;
                                                                        }

                                                                        else
                                                                        if($value->disposition_id == '104')
                                                                        {
                                                                            echo "Cancelled By User";
                                                                            break;
                                                                        }

                                                                        else
                                                                            if($value->disposition_id == '105')
                                                                            {
                                                                                $disposition_name = "Channel Unavailable";
                                                                                break;
                                                                            }
                                                                            else
                                                                            if($value->disposition_id == '106')
                                                                            {
                                                                                $disposition_name = "Congestion";
                                                                                break;
                                                                            }
                                                                            else
                                                                            if($value->disposition_id == '107')
                                                                            {
                                                                                $disposition_name = "Line Busy";
                                                                                break;
                                                                            }

                                                                    }
                                                                } else {
                                                                    echo 'N/A';
                                                                }
                                                                ?></td>
                                                                <td><?php echo gmdate("H:i:s", $value->duration); ?></td>
                                                                <td> @foreach($area_codes as $key => $area)
                                                                @if($area->areacode == $value->area_code)
                                                                {{$area->state_name}} / {{$area->city_name}}
                                                                
                                                                    @endif
                                                                @endforeach</td>
                                                                <td><?php echo $start_time; ?></td>
                                                            <td><?php echo $end_time;?></td>
                                                            <td>
                                                                <audio controls preload ='none'style="height:35px;width:220px;"><source src="<?php echo $value->call_recording; ?>" type='audio/wav'></audio>
                                                            </td>
                            
                                                                    
                                                                    <td>
                                                                        <a target="_blank" title="View Lead Record" href="/lead-activity?phone_number=<?php echo $value->number; ?>"><i  class="fa fa-eye fa-lg" aria-hidden="true"></i></a>
                                                                    </td>

                                                                   
                                                                    @if(Session::get('level') == 11 && $callchex == 1 && $callchex_status == 1)
 

                                                                     <td>
                                                                      <?php
$campaign_name = 'N/A';
if (!empty($value->campaign_id)) {
    foreach ($campaign_list as $campaign) {
        if ($campaign->id == $value->campaign_id && !empty($campaign->title)) {
            $campaign_name = $campaign->title;
            break;
        }
    }
}
?>
<?php
$ext_name = 'N/A';
if (!empty($value->extension)) {
    foreach ($extension_list as $extension) {
        if ($extension->extension == $value->extension || $extension->alt_extension == $value->extension) {
            $ext_name = $extension->first_name . ' ' . $extension->last_name;
            break;
        }
    }

    if ($ext_name === 'N/A') {
        $num = $value->extension;
        if (strlen((string) $num) > 9) {
            $ext_name = $value->extension;
        }
    }
}
?>

<a type="button"
   style="cursor:pointer;"
   data-id="{{ $value->id }}"
   data-industry_id="{{ $value->industry_id }}"
   data-lead_phone_number="{{ $value->number }}"
   data-agent_name="{{ $ext_name}}"
   data-audio_url="{{ $value->call_recording }}"
   data-agent_id="{{ $value->extension }}"
   data-from_number="{{ $value->cli }}"
   data-start_timestamp="{{ $value->start_time}}"
   data-end_timestamp="{{ $value->end_time }}"
   data-campaign_id="{{ $value->campaign_id }}"
   data-campaign_name="{{ $campaign_name }}"
   data-call_status="{{ $value->amd_status }}"
   data-recording_url="{{ $value->call_recording }}"
  data-reference_id="{{ $value->call_matrix_reference_id }}"

   data-bs-toggle="modal"
   data-bs-target="#myModal"
   class="list-icons-item me-10 view-report">
   <i class="fa fa-eye fa-lg"></i>
</a>

                                                                            <!-- <a  type="button" style="cursor:pointer;"data-bs-toggle="modal" data-bs-target="#myModal" data-id="{{$value->id}}" class="list-icons-item me-10 view-report"><i class="fa fa-eye fa-lg"></i></a> -->
                                                                           

                                                                        <!-- <a target="_blank" title="Analyze" href="/transcription_new.php?audio_url=<?php echo $value->call_recording; ?>"><i style="margin-top: 20px;margin-left: 10px;" class="fa fa-eye fa-lg" aria-hidden="true"></i></a> -->
                                                                    </td>
                                                                @endif
                    
                                            
                                    
                                        </tr>
                                        <?php } ?>


                                
                            </tbody>
                         
                        </table>
                        
                        <div style="float:right;">
                          {{$paginator->appends(Request::all())->links('pagination::bootstrap-5')}}


                                                            </div>
                                 <!-- Modal -->
<div id="myModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Call Matrix Report</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>

      <div class="modal-body" id="modalContent">
        <!-- <div class="text-center">Loading...</div> -->
      </div>
    </div>
  </div>
</div>

                        </div>
                </div>
                
            </div>
        </div>
        <?php } ?>

        </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>
    function callButton(value)
    {
        $("#show_value").val(value);
        $('#form_submit').trigger('click'); 
    }
</script>
 

<script>
    var myAudio = document.getElementById("myAudio");
    var isPlaying = false;

function togglePlay(valued) {
    $("#pause_"+valued).show();
    $("#play_"+valued).hide();

  isPlaying ? myAudio.pause() : myAudio.play();
};

function togglePause(valued) {
    $("#pause_"+valued).hide();
    $("#play_"+valued).show();

 myAudio.pause();
};

myAudio.onplaying = function() {
  isPlaying = true;
};
myAudio.onpause = function() {
  isPlaying = false;
};
</script>
<script type="text/javascript">
    $(function () {
        var startDate = "{{ $startDate }}";
        var endDate = "{{ $endDate }}";
        $('#reservation2').daterangepicker({
            locale: { format: 'YYYY-MM-DD' },
            autoUpdateInput: false, // Prevent auto-filling the input field
            opens: 'right'
        }, function (start, end) {
            $('#start_date').val(start.format('YYYY-MM-DD'));
            $('#end_date').val(end.format('YYYY-MM-DD'));
            $('#reservation2').val(start.format('YYYY-MM-DD') + ' - ' + end.format('YYYY-MM-DD')); // 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) {
            $('#reservation2').data('daterangepicker').setStartDate(startDate);
            $('#reservation2').data('daterangepicker').setEndDate(endDate);
            $('#reservation2').val(startDate + ' - ' + endDate);
        } else {
            $('#reservation2').val(''); // Ensure the input field is empty initially
        }
    });
</script>
<script>
// $(document).ready(function () {
//   $('.view-report').on('click', function () {
//     const $btn = $(this);

//     const data = {
//       id: $btn.data('id'),
//       industry_id: 1,
//       lead_phone_number: $btn.data('lead_phone_number'),
//       agent_name: $btn.data('agent_name'),
//       audio_url: $btn.data('audio_url'),
//       agent_id: $btn.data('agent_id'),
//       from_number: $btn.data('from_number'),
//       start_timestamp: $btn.data('start_timestamp'),
//       end_timestamp: $btn.data('end_timestamp'),
//       campaign_id: $btn.data('campaign_id'),
//       campaign_name: $btn.data('campaign_name'),
//       call_status: $btn.data('call_status'),
//       recording_url: $btn.data('recording_url'),
//       _token: $('meta[name="csrf-token"]').attr('content')
//     };

//     const referenceId = $btn.data('reference_id');
//     //alert(referenceId)
//     const id = $btn.data('id');

//     $('#modalContent').html('<div class="text-center">Audio processing has started. Please wait..</div>');
//     $('#myModal').modal('show');

//     if (!referenceId || referenceId === 'null' || referenceId === '') {
//       // 🔸 No reference ID: Call process API
//       $.ajax({
//         url: `/call-matrix-report/${id}`,
//         method: 'POST',
//         // contentType: 'application/json',
//         data: data,
//   headers: {
//         'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') // ✅ Correct CSRF token
//     },        success: function (res) {
//             console.log(res);
//           if (res.success && res.reference_id) {
//          toastr.success("UUID created successfully");
//  // Update the button’s data-reference_id so it won't call POST again
//             $btn.data('reference_id', res.reference_id);
//           fetchMatrixReport(res.reference_id);          
//         } else {
//             $('#modalContent').html('<div class="alert alert-danger">Error: Could not process data.</div>');
//           }
//         },
//         error: function () {
//           $('#modalContent').html('<div class="alert alert-danger">Failed to contact processing API.</div>');
//         }
//       });
//     } else {
//       // 🔹 reference ID exists: Call view API
//       fetchMatrixReport(referenceId);
//     }

//     // 🔹 Common fetch function for loading report
//     function fetchMatrixReport(referenceId) {
//       $.ajax({
//         url: `/call-matrix-report/${referenceId}`,
//         method: 'GET',
//         success: function (res) {
//           if (res.success && res.data) {
//             $('#modalContent').html(renderModalHtml(res.data));
//           } else {
//             $('#modalContent').html('<div class="alert alert-warning">No report data found.</div>');
//           }
//         },
//         error: function () {
//           $('#modalContent').html('<div class="alert alert-danger">Failed to load matrix report.</div>');
//         }
//       });
//     }
//     function renderModalHtml(data) {
//   const report = data[0]; // Single report object

//   // Lead Score Summary (above table)
//   let leadHtml = `
//     <h5 class="mt-3">🔹 Lead Scorecards</h5>
//     <div class="mb-2">
//       <strong>Score:</strong> ${report.total_score}/${report.max_score} &nbsp; | &nbsp;
//       <strong>Percentage:</strong> ${report.percentage}%
//     </div>
//     <table class="table table-bordered">
//       <thead>
//         <tr>
//           <th>Category</th>
//           <th>Score</th>
//           <th>Notes</th>
//         </tr>
//       </thead>
//       <tbody>
//   `;

//   report.lead_scorecards.forEach(item => {
//     leadHtml += `
//       <tr>
//         <td>${item.category}</td>
//         <td>${item.score_display}</td>
//         <td>${item.notes}</td>
//       </tr>
//     `;
//   });

//   leadHtml += `
//       </tbody>
//     </table>
//     <div class="mt-2">
//       <strong>Lead Category:</strong> ${report.lead_category_emoji} <br>
//       <strong>Description:</strong> ${report.lead_category_desc}
//     </div>
//   `;

//   // Agent Score Summary (above table)
//   let agentHtml = `
//     <h5 class="mt-4">🔸 Agent Metrics</h5>
//     <div class="mb-2">
//       <strong>Score:</strong> ${report.agent_total_score}/${report.agent_max_score} &nbsp; | &nbsp;
//       <strong>Average:</strong> ${report.agent_average_score}
//     </div>
//     <table class="table table-bordered">
//       <thead>
//         <tr>
//           <th>Category</th>
//           <th>Score</th>
//           <th>Notes</th>
//         </tr>
//       </thead>
//       <tbody>
//   `;

//   report.agent_metrics.forEach(item => {
//     agentHtml += `
//       <tr>
//         <td>${item.category}</td>
//         <td>${item.score_display}</td>
//         <td>${item.notes}</td>
//       </tr>
//     `;
//   });

//   agentHtml += `
//       </tbody>
//     </table>
//     <div class="mt-2">
//       <strong>Coaching Recommendation:</strong><br>${report.coaching_recommendation}
//     </div>
//   `;

//   return `
//     <div>
//       ${leadHtml}
//       ${agentHtml}
//     </div>
//   `;
// }
//   });
// });

$('.view-report').on('click', function () {
  const $btn = $(this);
  const id = $btn.data('id');
  let referenceId = $btn.data('reference_id');

  $('#modalContent').html('<div class="text-center my-3">Audio processing has started. Please wait...</div>');
  $('#myModal').modal('show');

  // Call POST if reference ID is not available
  if (!referenceId || referenceId === 'null' || referenceId === '') {
    $.ajax({
      url: `/call-matrix-report/${id}`,
      method: 'POST',
      data: {
        id: id,
        industry_id: 247,
        lead_phone_number: $btn.data('lead_phone_number'),
        agent_name: $btn.data('agent_name'),
        audio_url: $btn.data('audio_url'),
        agent_id: $btn.data('agent_id'),
        from_number: $btn.data('from_number'),
        start_timestamp: $btn.data('start_timestamp'),
        end_timestamp: $btn.data('end_timestamp'),
        campaign_id: $btn.data('campaign_id'),
        campaign_name: $btn.data('campaign_name'),
        call_status: $btn.data('call_status'),
        recording_url: $btn.data('recording_url'),
        _token: $('meta[name="csrf-token"]').attr('content')
      },
      headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      },
      success: function (res) {
        if (res.success && res.reference_id) {
          referenceId = res.reference_id;
          $btn.data('reference_id', referenceId); // Store for future use

          toastr.success("Analysis created successfully");

          // Now show the "View Report" button inside modal
          $('#modalContent').html(`
            <div class="text-center my-3">
              <p>Click the button below to view the report.</p>
              <button id="showViewData" class="btn btn-primary">View Report</button>
            </div>
          `);

          // Bind the click to that button
          $(document).off('click', '#showViewData').on('click', '#showViewData', function () {
            fetchMatrixReport(referenceId);
          });

        } else {
          $('#modalContent').html('<div class="alert alert-danger">Error: Could not process data.</div>');
        }
      },
      error: function () {
        // $('#modalContent').html('<div class="alert alert-danger">Failed to contact processing API.</div>');
      }
    });
  } else {
    // If already has reference_id, skip POST and go to view directly
    fetchMatrixReport(referenceId);
  }

  function fetchMatrixReport(referenceId) {
    $('#modalContent').html('<div class="text-center my-3">Loading report...</div>');
    $.ajax({
      url: `/call-matrix-report/${referenceId}`,
      method: 'GET',
      success: function (res) {
        if (res.success && res.data) {
          $('#modalContent').html(renderModalHtml(res.data));
        } else {
          $('#modalContent').html('<div class="alert alert-warning">No report data found.</div>');
        }
      },
      error: function () {
        $('#modalContent').html('<div class="alert alert-danger">The report is currently being processed. Please try again shortly</div>');
      }
    });
  }

  function renderModalHtml(data) {
    const report = data[0];

    let leadHtml = `
      <h5 class="mt-3">🔹 Lead Scorecards</h5>
      <div class="mb-2">
        <strong>Score:</strong> ${report.total_score}/${report.max_score} &nbsp; | &nbsp;
        <strong>Percentage:</strong> ${report.percentage}%
      </div>
      <table class="table table-bordered">
        <thead><tr><th>Category</th><th>Score</th><th>Notes</th></tr></thead>
        <tbody>`;

    report.lead_scorecards.forEach(item => {
      leadHtml += `<tr><td>${item.category}</td><td>${item.score_display}</td><td>${item.notes}</td></tr>`;
    });

    leadHtml += `</tbody></table>
      <div class="mt-2"><strong>Lead Category:</strong> ${report.lead_category_emoji}<br>
      <strong>Description:</strong> ${report.lead_category_desc}</div>`;

    let agentHtml = `
      <h5 class="mt-4">🔸 Agent Metrics</h5>
      <div class="mb-2">
        <strong>Score:</strong> ${report.agent_total_score}/${report.agent_max_score} &nbsp; | &nbsp;
        <strong>Average:</strong> ${report.agent_average_score}
      </div>
      <table class="table table-bordered">
        <thead><tr><th>Category</th><th>Score</th><th>Notes</th></tr></thead>
        <tbody>`;

    report.agent_metrics.forEach(item => {
      agentHtml += `<tr><td>${item.category}</td><td>${item.score_display}</td><td>${item.notes}</td></tr>`;
    });

    agentHtml += `</tbody></table>
      <div class="mt-2"><strong>Coaching Recommendation:</strong><br>${report.coaching_recommendation}</div>`;

    return `<div>${leadHtml}${agentHtml}</div>`;
  }
});

</script>
<!-- <script new>
$(document).ready(function () {
  $('.view-report').on('click', function () {
    const cdrId = $(this).data('id');
    $('#modalContent').html('<div class="text-center">Loading...</div>');

    $.ajax({
      url: `/call-matrix-report/${cdrId}`,
      method: 'POST',
      success: function (response) {
        if (response.success && response.data.length > 0) {
          const leadReports = response.data.filter(item => item.report_type === 'lead');
          const agentReports = response.data.filter(item => item.report_type === 'agent');
          const leadSummary = response.data.find(item => item.report_type === 'summary' && item.category === 'Lead Summary');
          const agentSummary = response.data.find(item => item.report_type === 'summary' && item.category === 'Agent Summary');

          let html = '';

          // 🔹 Lead Table
          if (leadReports.length > 0) {
            html += '<h5>Lead Scorecard</h5><table class="table table-bordered">';
            html += '<thead><tr><th>Category</th><th>Score</th><th>Notes</th></tr></thead><tbody>';
            leadReports.forEach(item => {
              html += `<tr>
                <td>${item.category}</td>
                <td>${item.score_display ?? 'N/A'}</td>
                <td>${item.notes ?? '—'}</td>
              </tr>`;
            });
            html += '</tbody></table>';
          }

          // 🔹 Lead Summary
          if (leadSummary) {
            html += `
              <h6>Lead Summary</h6>
              <p><strong>Total Score:</strong> ${leadSummary.total_score ?? '—'}</p>
              <p><strong>Max Score:</strong> ${leadSummary.max_score ?? '—'}</p>
              <p><strong>Percentage:</strong> ${leadSummary.percentage ?? '—'}%</p>
              <p><strong>Emoji:</strong> ${leadSummary.summary_emoji ?? ''}</p>
              <p><strong>Description:</strong> ${leadSummary.summary_description ?? '—'}</p>
              <p><strong>Coaching Recommendation:</strong> ${leadSummary.coaching_description ?? '—'}</p>
              <hr/>
            `;
          }

          // 🔹 Agent Table
          if (agentReports.length > 0) {
            html += '<h5>Agent Performance</h5><table class="table table-bordered">';
            html += '<thead><tr><th>Category</th><th>Score</th><th>Notes</th></tr></thead><tbody>';
            agentReports.forEach(item => {
              html += `<tr>
                <td>${item.category}</td>
                <td>${item.score_display ?? 'N/A'}</td>
                <td>${item.notes ?? '—'}</td>
              </tr>`;
            });
            html += '</tbody></table>';
          }

          // 🔹 Agent Summary
          if (agentSummary) {
            html += `
              <h6>Agent Summary</h6>
              <p><strong>Total Score:</strong> ${agentSummary.total_score ?? '—'}</p>
              <p><strong>Max Score:</strong> ${agentSummary.max_score ?? '—'}</p>
              <p><strong>Average Score:</strong> ${agentSummary.average_score ?? '—'}</p>
              <hr/>
            `;
          }

          $('#modalContent').html(html);
        } else {
          $('#modalContent').html('<div class="alert alert-warning">No report data found.</div>');
        }
      },
      error: function () {
        $('#modalContent').html('<div class="alert alert-danger">Failed to load data.</div>');
      }
    });
  });
});
</script> -->


<!-- <script>
$(document).ready(function() {
  $('.view-report').on('click', function() {
    const cdrId = $(this).data('id');
    $('#modalContent').html('<div class="text-center">Loading...</div>');

    $.ajax({
      url: `/call-matrix-report/${cdrId}`,
      method: 'GET',
      success: function(response) {
        console.log(response);
        if (response.success && response.data.length > 0) {
          const leadReports = response.data.filter(item => item.report_type === 'lead');
          const agentReports = response.data.filter(item => item.report_type === 'agent');
          const summaries = response.data.filter(item => item.report_type === 'summary');

          let html = '';

          // 🔵 Lead Scorecard Table
          if (leadReports.length > 0) {
            html += '<h5>Lead Scorecard</h5><table class="table table-bordered">';
            html += '<thead><tr><th>Category</th><th>Score</th><th>Notes</th></tr></thead><tbody>';
            leadReports.forEach(report => {
              html += `<tr>
                <td>${report.category}</td>
                <td>${report.score_display ?? 'N/A'}</td>
                <td>${report.notes ?? '—'}</td>
              </tr>`;
            });
            html += '</tbody></table>';
          }

          // 🔵 Agent Performance Table
          if (agentReports.length > 0) {
            html += '<h5>Agent Performance</h5><table class="table table-bordered">';
            html += '<thead><tr><th>Category</th><th>Score</th><th>Notes</th></tr></thead><tbody>';
            agentReports.forEach(report => {
              html += `<tr>
                <td>${report.category}</td>
                <td>${report.score_display ?? 'N/A'}</td>
                <td>${report.notes ?? '—'}</td>
              </tr>`;
            });
            html += '</tbody></table>';
          }

          // 🔵 Summary Sections
          if (summaries.length > 0) {
            summaries.forEach(summary => {
              html += `<h5>${summary.category}</h5>
                <p><strong>Total Score:</strong> ${summary.total_score ?? '—'}</p>
                <p><strong>Max Score:</strong> ${summary.max_score ?? '—'}</p>
                ${summary.average_score ? `<p><strong>Average Score:</strong> ${summary.average_score}</p>` : ''}
                ${summary.percentage ? `<p><strong>Percentage:</strong> ${summary.percentage}%</p>` : ''}
                ${summary.summary_emoji ? `<p><strong>Emoji:</strong> ${summary.summary_emoji}</p>` : ''}
                ${summary.summary_description ? `<p><strong>Description:</strong> ${summary.summary_description}</p>` : ''}
                ${summary.coaching_description ? `<p><strong>Coaching Recommendation:</strong> ${summary.coaching_description}</p>` : ''}
                <hr/>`;
            });
          }

          $('#modalContent').html(html);
        } else {
          $('#modalContent').html('<div class="alert alert-warning">No report data found.</div>');
        }
      },
      error: function(xhr) {
        $('#modalContent').html('<div class="alert alert-danger">Failed to load data.</div>');
      }
    });
  });
});
</script> -->



@endpush

@endsection



