
@extends('layouts.app')
@section('title', 'Crm Dashboard')
@section('content')
<link href="{{asset('assets/css/bootstrap4-toggle.min.css')}}" rel="stylesheet">
@push('styles')

<!-- daterange picker -->
<link rel="stylesheet" href="{{asset('assets/plugins/daterangepicker/daterangepicker-bs3.css') }}">
<!-- <link rel="stylesheet" href="{{asset('assets/plugins/dashboard_date/daterangepicker.css') }}"> -->

<!-- bootstrap datetimepicker -->
<link rel="stylesheet"
    href="{{asset('assets/plugins/bootstrap-datetimepicker/css/bootstrap-datetimepicker.min.css') }}">
<!-- <link rel="stylesheet" href="{{asset('assets/plugins/dashboard_date/bootstrap-datepicker.min.css') }}"> -->
<link rel="stylesheet" href="{{asset('assets/plugins/datatables/dataTables.bootstrap.min.css') }}">



@endpush
<section class="content">
<?php
error_reporting(0);
$startDate = request()->input('start_date') ?? '';
$endDate = request()->input('end_date') ?? '';

?>


<div class="row">
        <div class="col-xl-12 col-12">
            <div class="row leadStatusbox">

                </div>
                <!-- <a  style="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><br><br> -->
            <div class="row">
        

  
</div>
           
            <!-- <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" style="background:white;padding:10px;"> -->
<div class="collapse mt-3" id="filterCard">
                        <div class="card filter-card mb-4">

        <button type="button" class="btn-close position-absolute top-0 end-0 m-3" aria-label="Close" 
            onclick="document.getElementById('filterCard').classList.remove('show');">
        </button>
                        <div class="card-body">
                        <form id="leadForm1">
                          @csrf
                        <div class="row">
                   

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

                                    <input class="form-control " value="{{request()->input('first_name')}}" name="first_name" id="" placeholder="First Name">
                                </div>
                            </div>
                            <div class="form-group col-md-3">
                              <label class="form-label">Last Name</label>
                                <div class="input-group">
                                <span class="input-group-text @error('last_name') text-danger border-danger @enderror"><i class="ti-user"></i></span>

                                    <input class="form-control " value="{{request()->input('last_name')}}" name="last_name" id="" placeholder="Last Name">
                                </div>
                            </div>
                            <div class="form-group col-md-3">
                                <div class="form-group">
                                    <label class="form-label">DBA</label>
                                    <input  type="text" class="form-control " value="{{request()->input('dba')}}" name="dba" id="dba" placeholder="DBA">
                                </div>
                            </div>
                          
                          
                            <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">Email</label>
                                <div class="input-group">
                                <span class="input-group-text @error('email') text-danger border-danger @enderror"><i class="ti-user"></i></span>

                                    <input type="email"class="form-control " value="{{request()->input('email')}}" name="email" id="email" placeholder="Email">
                                </div>
                            </div>
                            <div class="form-group col-md-3">
                              <label class="form-label">Company Name</label>
                                <div class="input-group">
                                <span class="input-group-text @error('company_name') text-danger border-danger @enderror"><i class="ti-user"></i></span>

                                    <input class="form-control " value="{{request()->input('company_name')}}" name="company_name" id="company_name" placeholder="Company Name">
                                </div>
                            </div>
                            <div class="form-group col-md-3">
                              <label class="form-label">Lead Status</label>
                              <div class="input-group">
                                    <select class="select2 form-control" name="lead_status[]" id="lead_status" multiple="multiple" style="width:100%">
                                     
                                    </select>                               
                                   </div>
                            </div>
                            <div class="form-group col-md-3">
                              <label class="form-label">Assigned to</label>
                                <div class="input-group">
                                    <select class="select2 form-control" name="assigned_to[]" id="assigned_to"  multiple="multiple" style="width:100%">
                                 
                                    </select>
                                </div>
                            </div>
                            <div class="form-group col-md-3">
                              <label class="form-label">Lead Type</label>
                                <div class="input-group">
                                    <select class="select2 form-control" name="lead_type[]" id="lead_type" multiple="multiple" style="width:100%">
                                        <option @if(empty(request()->input('lead_type'))) @elseif(in_array('hot', request()->input('lead_type'))) selected @endif  value="hot">Hot</option>
                                        <option @if(empty(request()->input('lead_type'))) @elseif(in_array('warm', request()->input('lead_type'))) selected @endif   value="warm">Warm</option>
                                        <option @if(empty(request()->input('lead_type'))) @elseif(in_array('cold', request()->input('lead_type'))) selected @endif   value="cold">Cold</option>
                                    </select>
                                </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="reservation1">
                      <input type="hidden" id="start_date" name="start_date" value="{{ $startDate }}">
                      <input type="hidden" id="end_date" name="end_date" value="{{ $endDate }}">  

                      </div>
                       <!-- Hidden input to indicate download -->
                          </div>
                            <div class="box-footer text-end">
        
                            <button type="button" class="btn btn-warning" id="downloadExcelButton">
            <i class="fa fa-file-text"></i> Excel
        </button>
                                <!-- <a href="{{ url('crm-dashboard?download=excel') }}" type="button"  class="btn btn-warning"><i class="fa fa-file-text"></i> Excel</a> -->
                <a onclick="resetFilter();"  class="btn btn-danger me-1">
                  <i class="ti-reload"></i> Reset
                </a>

                <button  type="submit" class="btn btn-primary"id="submitForm">
                  <i class="ti-save-alt"></i> Submit
                </button>
              </div>    
  </form>

  </div>
</div>
    </div>
                          <!-- </div>
                        </div>
                      </div> -->
                    </div>

<style>

.filter-card {
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  border: 1px solid #e5e5e5;
}


.filter-card .card-body {
  padding: 20px;
  background: #fff;
}

.filter-card + .card {
  margin-top: 20px;
}

/* === Toggle Button === */
.status-toggle {
    position: relative;
    display: flex;
    justify-content: space-between;
    width: 260px; 
    margin: 0 auto;
    background: #f4f4f4;
    border-radius: 30px;
    padding: 4px;
    font-weight: 600;
    font-size: 14px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}

.status-toggle .toggle-option {
    flex: 1;
    text-align: center;
    padding: 8px 0;
    cursor: pointer;
    position: relative;
    z-index: 3 !important;
    color: #333;
    transition: color 0.3s ease;
    border-radius: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
}

.status-toggle .toggle-option i {
    font-size: 14px;
    display: inline-block;
}

.status-toggle .toggle-option.active {
    color: #fff;
}

.status-toggle .toggle-indicator {
    position: absolute;
    top: 4px;
    bottom: 4px;
    width: calc(33.33% - 8px);
    border-radius: 20px;
    transition: all 0.3s ease;
    z-index: 0;
}

/* Gradient Colors */
.status-toggle .toggle-option[data-status="Hot"].active ~ .toggle-indicator {
    left: 4px;
    background: linear-gradient(45deg, #ff4d4d, #ff0000);
}
.status-toggle .toggle-option[data-status="Warm"].active ~ .toggle-indicator {
    left: calc(33.33% + 4px);
    background: linear-gradient(45deg, #f39c12, #f1c40f);
}
.status-toggle .toggle-option[data-status="Cold"].active ~ .toggle-indicator {
    left: calc(66.66% + 4px);
    background: linear-gradient(45deg, #2980b9, #3498db);
}

/* === Table + Card === */
/* table thead {
    background: linear-gradient(45deg, #673ab7, #2196f3);
    color: #fff;
} */

table thead th {
    text-align: center;
    font-weight: 600;
    padding: 4px 8px;  
    line-height: 1;    
    white-space: nowrap;
}

.card {
    border: none;
    border-radius: 10px !important;
    box-shadow: 0 4px 10px rgba(0,0,0,0.1);
    padding-left: 15px !important;
    padding-right: 15px !important;
}

.table {
    margin-bottom: 0;
    width: 100%;
}

.table td, .table th {
    padding: 8px 10px;
    text-align: center;
    vertical-align: middle;
    font-size: 14px;
}

.filter-btn {
    position: relative;
    left: -10px !important;  
    border-radius: 6px !important;
    padding: 6px 12px;
}

#leadData .table-responsive {
    overflow-x: visible !important;   
}

#leadData table {
    table-layout: auto;              
    width: 100% !important;          
    white-space: normal;           
}

#leadData table td, 
#leadData table th {
    word-wrap: break-word;         
    white-space: normal;
}

.dataTables_wrapper .dataTables_length,
.dataTables_wrapper .dataTables_filter {
    position: sticky;
    top: 0; 
    background: #fff;
    z-index: 10;
    padding: 8px 12px;
}


.dataTables_wrapper table {
    margin-top: 10px;
}



/* Tablet (max-width: 992px) */
@media (max-width: 992px) {
  .form-group.col-md-3 {
    flex: 0 0 50%;
    max-width: 50%;   
  }

  .status-toggle {
    width: 220px;  
    font-size: 13px;
  }

  .filter-btn {
    margin-left: 0 !important;
    margin-top: 10px;
  }

  #leadData .table-responsive {
    overflow-x: auto !important; 
  }
}

/* Mobile (max-width: 576px) */
@media (max-width: 576px) {
  .form-group.col-md-3 {
    flex: 0 0 100%;
    max-width: 100%;   
  }

  .status-toggle {
    width: 100%;  
    margin-bottom: 10px;
  }

  .d-flex.align-items-center.justify-content-between {
    flex-direction: column;
    gap: 10px;
  }


  #leadData .table-responsive {
    overflow-x: auto !important;
  }
}

@media (max-width: 576px) {
  .filter-btn {
    display: block;
    width: 100% !important;
    max-width: 100% !important;
    margin: 10px 0 0 0 !important;
    text-align: center;
    float: none !important;
    position: relative !important;
    left: 0 !important;
    right: 0 !important;
    box-sizing: border-box;
  }

  .filter-btn.parent, 
  .dataTables_wrapper, 
  .dataTables_filter {
    padding-left: 10px !important;
    padding-right: 10px !important;
  }
}

@media (max-width: 576px) {
  #ticket_filter {
    position: relative !important;
    width: 100% !important;
    max-width: 95% !important;
    margin: 10px 0 0 0 !important;
    left: -45px !important;
    right: 0 !important;
    box-sizing: border-box;
  }

  #ticket_filter input {
    width: 100% !important;
  }
}


@media (max-width: 992px) {
  #ticket_filter {
    position: relative !important;
    width: 220px !important;
    margin-right: 10px !important;
    top: auto !important;
    right: auto !important;
    box-sizing: border-box;
  }

  #ticket_filter input {
    width: 100% !important;
  }

  .d-flex.align-items-center.justify-content-between {
    flex-wrap: wrap;
    gap: 10px;
  }
}

/* Tablet */
@media (max-width: 992px) {
  .leadStatusbox {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    justify-content: space-around;
  }

  .leadStatusbox .card {
    flex: 0 0 calc(50% - 15px); 
    max-width: calc(50% - 15px);
  }
}

/* Mobile */
@media (max-width: 576px) {
  .leadStatusbox {
    display: flex;
    flex-direction: column;
    gap: 12px;
    align-items: center;
  }

  .leadStatusbox .card {
    flex: 0 0 100%;  
    max-width: 100%;
  }
}

/* Tablet + Mobile */
@media (max-width: 768px) {
  .dataTables_length, 
  .dataTables_filter { 
    width: 100%;
    text-align: left !important;
    margin-bottom: 10px;
  }

  .dataTables_filter {
    text-align: right !important;
  }

  .dataTables_length select {
    width: auto;
    display: inline-block;
  }
}



@media (max-width: 991px) {
  .lead-status-item {
    width: 100% !important;
    margin-bottom: 10px;
  }

  .lead-status-item .box {
    font-size: 20px !important; 
    padding: 10px !important;
  }

  .lead-status-item h5 {
    font-size: 12px !important;
    padding: 5px 0 0 !important;
  }

  .lead-status-item h2 {
    font-size: 18px !important;
  }

  .lead-status-item .d-flex {
    flex-direction: row;
    justify-content: space-between;
  }
}

/* #ticket td:last-child {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 6px;
}


#ticket td:last-child a {
    display: inline-flex; 
    width: auto !important; 
    margin: 0 !important;
} */

#ticket td {
    white-space: nowrap;   
    overflow: hidden;    
    text-overflow: ellipsis; 
    vertical-align: middle;
}


#ticket td:last-child {
    position: sticky;
    right: 0;
    background: #fff;
    z-index: 1;
    text-align: center;
    padding: 8px 8px;    
    vertical-align: middle;
    min-width: 80px;      
}


#ticket th:last-child {
    position: sticky;
    right: 0;
    background: #fff;
    /* color: #fff; */
    z-index: 2;
    text-align: center;
    padding: 12px 8px;    
    min-width: 80px;     
}

#ticket td:nth-child(3), #ticket th:nth-child(3) {
    padding: 8px 12px;
    min-width: 100px; 
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}


#ticket_filter {
    position: absolute;
    top: 7px;            
    right: 95px;          
    z-index: 10;
}


#ticket_filter input {
    width: 200px;         
    display: inline-block;
}


</style>




<div class="col-xl-12 col-12">
    <div class="card shadow rounded-3">
        <div class="card-body p-0">

          <div class="d-flex align-items-center justify-content-between mt-2">
    <!-- Toggle -->
    <div class="status-toggle" id="statusFilter"> 
        <div class="toggle-option active" data-status="Hot"><i class="fa fa-fire"></i> Hot</div>
        <div class="toggle-option" data-status="Warm"><i class="fa fa-fire"></i> Warm</div>
        <div class="toggle-option" data-status="Cold"><i class="fa fa-fire"></i> Cold</div>
        <div class="toggle-indicator"></div>
    </div>

<a class="btn btn-primary btn-sm filter-btn float-end" 
   data-bs-toggle="collapse" 
   href="#filterCard" 
   aria-expanded="false" 
   aria-controls="filterCard">
   <i class="fa fa-search"></i> Filter
</a>


</div>


            <!-- Table (Dynamic Data Render Hogi) -->
            <!-- <div class="table-responsive" id="leadData" style="padding:20px;"> -->
                <!-- Dynamic Table Yahan Render Hogi -->
            <!-- </div> -->
              <div class="table-responsive">
<table id="ticket" class="table mt-0 table-hover">
    <thead>
        <tr id="ticket-head">
            <th>ID</th>
        </tr>
    </thead>
</table>
</div>
        </div>

        
    </div>
</div>


            </div>

 <style>
  .chart-container {
    display: flex;
    justify-content: space-between;
    align-items: stretch;
    gap: 20px;
    margin-top: 10px;
    margin-bottom: 25px;
  }

  .chart-card,
  .data-card {
    background: #fff;
    border-radius: 16px;
    box-shadow: 0px 4px 10px rgba(0,0,0,0.1);
    padding: 0; 
    overflow: hidden;
  }

  .chart-card {
    flex: 0 0 63%;
  }

  .chart-card h3 {
    margin: 0;
    padding: 18px 20px 12px 20px; 
    font-size: 18px;
    font-weight: 700;
    border-bottom: 1px solid rgba(0,0,0,0.05); 
  }

.chart-card canvas {
  width: 100% !important;
  height: 300px !important;
  display: block;
  box-sizing: border-box;
  padding: 10px 20px 0 20px;
}

  .data-card {
    flex: 0 0 35%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding: 20px;
  }

  .data-card canvas {
    max-width: 95%;
    max-height: 95%;
    margin: 0 auto;
  }
</style>


    <!-- <div class="box-tools pull-right"> -->

<style>
  @media (max-width: 1024px) {
    .chart-container {
      flex-wrap: wrap;
    }
    .chart-card,
    .data-card {
      flex: 0 0 100%;
      margin-bottom: 20px;
    }
    .chart-card canvas {
      height: 280px !important;
      padding: 10px 15px 0 15px;
    }
    .data-card .card-body {
      height: auto !important;
    }
    .data-card canvas {
      width: 100% !important;
      max-width: 300px;
      height: 250px !important; 
    }
  }

  @media (max-width: 768px) {
    .chart-card canvas {
      height: 250px !important;
      padding: 10px 10px 0 10px;
    }
    .data-card canvas {
      max-width: 250px;
      height: 200px !important;
    }
  }

  @media (max-width: 576px) {
    .chart-card canvas {
      height: 200px !important;
      padding: 5px 5px 0 5px;
    }
    .data-card canvas {
      max-width: 200px;
      height: 180px !important;
    }
    #customLegend {
      grid-template-columns: repeat(2, 1fr);
      gap: 8px;
      font-size: 12px;
    }
  }
</style>



    <div class="box-tools pull-right">
                        <!-- Date and time range -->
                        <!-- <div class="form-group">
                            <div class="input-group">
                                <button type="button" class="btn btn-primary btn-sm pull-right" id="daterange-btn">
                                    <span>
                                        <i class="fa fa-calendar"></i> Date range picker
                                    </span>
                                    <i class="fa fa-caret-down"></i>
                                </button>
                            </div>
                        </div>
                    </div> -->
<!-- <div class="chart-container"> -->
  <!-- Left Chart -->
  <!-- <div class="chart-card">
    <h3 style="margin-bottom: 20px;">📊 Daily Call Analysis</h3>
    <canvas id="dailyChart" style="width: 100%; height: 300px;"></canvas>
  </div> -->

  <!-- Right Pie Chart -->
  <!-- <div class="data-card">
    <div class="card-body" style="padding: 20px; height: 100%;">
      <div style="position: relative; width: 100%; height: 70%; display: flex; align-items: center; justify-content: center;">
        <canvas id="cardsChart"></canvas>
      </div>
      <div id="customLegend"
        style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; margin-top: 20px; text-align: left;">
      </div>
      <p id="noDataMsg" style="text-align:center;color:#6B7280;display:none;">
    <b>No data  found</b>
</p>
    </div>
  </div>
</div> -->

<!-- <div class="card shadow-lg border-0" 
     style="max-width: 500px; aspect-ratio: 1/1; margin: 20px 0 20px auto;">
  <div class="card-body" style="padding: 20px; height: 80%;">
   
    <div style="position: relative; width: 100%; height: 65%;">
      <canvas id="cardsChart" style="width: 100% !important; height: 100% !important;"></canvas>
    </div>

    <div id="customLegend"
      style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; margin-top: 60px; text-align: left;">
    </div>
  </div>
</div> -->


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


<div class="modal fade" id="delete" tabindex="-1" aria-labelledby="deleteLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="myModalLabel">Confirm Delete</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
     

      <div class="modal-body">
      <p>You are about to delete <b><i class="title"></i></b> lead.</p>
                                <p>Do you want to proceed?</p>                       
                                <input type="hidden" class="form-control" name="lead_id" value="" id="lead_id">

          </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-danger btn-ok btn-sm deleteLead">Delete</button>
      </div>
    </div>
  </div>
</div>	

<!-- <style>
.dataTables_processing {
    margin-top: 30px !important; 
    text-align: center !important;

}

</style> -->


</section>


@push('scripts')


<!-- SlimScroll 1.3.0 -->
<script src="{{ asset('assets/plugins/slimScroll/jquery.slimscroll.min.js?ver=0.0.1') }}"></script>

<!-- ChartJS 1.0.1 -->
<!--  <script src="{{asset('assets/js/Chart.min.js?ver=0.0.1')}}"></script> -->

<!-- date-range-picker -->
<script src="{{asset('assets/plugins/dashboard_date/moment.min.js?ver=0.0.1') }}"></script>
<script src="{{asset('assets/plugins/dashboard_date/daterangepicker.js?ver=0.0.1') }}"></script>

<!-- bootstrap datepicker -->
<script src="{{asset('assets/plugins/dashboard_date/bootstrap-datepicker.min.js?ver=0.0.1') }}"></script>

<script src="{{asset('assets/plugins/datatables/jquery.dataTables.min.js?ver=0.0.1') }}"></script>
<script src="{{asset('assets/plugins/datatables/dataTables.bootstrap.min.js?ver=0.0.1') }}"></script>
<script src="{{ asset('assets/vendor_components/c3/d3.min.js')}}"></script>
<script src="{{ asset('assets/vendor_components/c3/c3.min.js')}}"></script>


<script src="{{ asset('assets/vendor_components/echarts/dist/echarts-en.min.js?ver=0.0.1')}}"></script>
<script src="{{asset('assets/js/bootstrap4-toggle.min.js')}}"></script>
@endpush
<script>
    
$(document).ready(function () {
    let headRow = $("#ticket-head");

    // ---- Build Columns (Dynamic + Static) ----
    let columns = [{ data: "id", name: "id" }];

    let dynamicColumns = @json(
        array_map(function($v) {
            return [
                'label_title' => $v->title,
                'column_name' => $v->column_name
            ];
        }, $view_on_leads)
    );

 dynamicColumns.forEach(function(view) {
    headRow.append("<th>" + view.label_title + "</th>");

    if (view.column_name === "phone_number") {
        columns.push({
            data: view.column_name,
            name: view.column_name,
            render: function (data, type, row) {
                if (!data) return '';
                let digits = data.replace(/\D/g, '');
                if (digits.length === 10) {
                    return '(' + digits.substring(0, 3) + ') ' +
                           digits.substring(3, 6) + '-' +
                           digits.substring(6);
                }
                return data; // fallback for non-10-digit numbers
            }
        });
    } else {
        columns.push({ data: view.column_name, name: view.column_name });
    }
});
headRow.append("<th>Status</th><th>Created At</th><th>Updated At</th>");

@if(Session::get("level") > 5)
    headRow.append("<th>Created By</th>");
@endif

headRow.append("<th>Assigned To</th><th>Action</th>");

columns.push(
    { data: "lead_status", name: "lead_status", orderable: false, searchable: false },
    { data: "created_at", name: "created_at" },
    { data: "updated_at", name: "updated_at" },

    @if(Session::get("level") > 5)
        { data: "created_by", name: "created_by" },
    @endif
    { data: "assigned_to", name: "assigned_to" },
    { data: "actions", name: "actions", orderable: false, searchable: false }
);


    // ---- Initialize DataTable ----
    let ticketTable = $('#ticket').DataTable({
        processing: true,
        serverSide: true,        
         searching: true, // Enable global search
        ajax: {
            url: '{{ url("crm-dashboard") }}',
            type: 'POST',
            data: function (d) {
                let formData = $('#leadForm1').serializeArray();
                formData.forEach(item => { d[item.name] = item.value; });
            }
        },
        columns: columns,
         order: [[0, 'desc']], // assuming the first column is 'id'

      language: {
    processing: `
        <span style="display:flex; align-items:center; justify-content:center; gap:8px;">
            <img src="https://i.gifer.com/ZZ5H.gif"
                 alt="Loading..." style="width:20px; height:20px;">
            Processing...
        </span>
    `
}

         
    });




    // ---- Helper: Reload Table ----
    function updateTableWithData() {
        ticketTable.ajax.reload(null, false);
    }

    // ---- Form Submit ----
    $('#leadForm1').off('submit').on('submit', function(event) {
        event.preventDefault();
        $('#loader').show();

        var formData = $(this).serializeArray();
        var isDownload = $(document.activeElement).attr('name') === 'submit_download';
        if (isDownload) formData.push({ name: 'submit_download', value: '1' });

        $.ajax({
            url: '{{ url("crm-dashboard") }}',
            method: 'POST',
            data: formData,
            success: function(response) {
                $('#loader').hide();
                if (isDownload && response.file_url) {
                    window.location.href = response.file_url; // Excel download
                } else {
                    updateTableWithData();
                }
            },
            error: function(xhr) {
                $('#loader').hide();
                console.error('Error:', xhr);
            }
        });
    });

    // ---- Excel Download ----
    $('#downloadExcelButton').on('click', function() {
        var formData = $('#leadForm1').serialize();
        var actionUrl = '{{ url("crm-dashboard") }}';
        window.location.href = actionUrl + '?' + formData + '&submit_download=1';
    });

    // ---- Fill Dropdowns ----
    const leadStatuses   = @json($lead_status);
    const users          = @json($sortedUsers);
    const userLevel      = {{ Session::get('level') }};
    const currentUserId  = {{ Session::get('id') }};
    const currentUserName = "{{ Session::get('first_name') }} {{ Session::get('last_name') }}";
    const leadStatusList = @json($filteredLeadStatus);
    const leadStatusCount = @json($lead_status_count['leadstatus']);

    const leadStatusDropdown = $('#lead_status');
    leadStatuses.forEach(s => {
        leadStatusDropdown.append(`<option value="${s.lead_title_url}">${s.title}</option>`);
    });

    const assignedToDropdown = $('#assigned_to');
    if (userLevel > 5) {
        users.forEach(u => {
            if (u.is_deleted == '0' && u.user_level < 9) {
                assignedToDropdown.append(`<option value="${u.id}">${u.first_name} ${u.last_name}</option>`);
            }
        });
    } else {
        assignedToDropdown.append(`<option value="${currentUserId}">${currentUserName}</option>`);
    }
    $('.select2').select2();

    // ---- Build Lead Status Boxes ----
$('.leadStatusbox').empty();

$.each(leadStatusList, function (i, leadStatus) {
    // Match lead_title_url with lead_status field in counts
    var matchingCounts = leadStatusCount.filter(function(c) {
        return c.lead_status === leadStatus.lead_title_url;
    });

    var totalLeadStatus = matchingCounts.reduce(function(sum, c) {
        return sum + (c.total_lead_status || 0);
    }, 0);

    var bgColor = leadStatus.color_code || "#28a745"; // fallback green

    var titleDiv = $('<div>')
        .addClass('col-lg-3 col-12 lead-status-item')
        .css('width', '20%')
        .attr('data-lead-status', leadStatus.lead_title_url)
        .append(`
            <div class="box" style="font-size:30px;color:white;background-color:${bgColor}">
                <div class="box-body py-0">
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="lead-status-content">
                            <h5 style="color:white;font-weight:500;padding:10px 0 0;font-size:13px;">
                                ${leadStatus.title}
                            </h5>
                            <h2 style="color:white;" class="fw-500 mb-0">${totalLeadStatus}</h2>
                        </div>
                        <div><i class="fa fa-user"></i></div>
                    </div>
                </div>
            </div>
        `);

    $('.leadStatusbox').append(titleDiv);
});

    $('.leadStatusbox .lead-status-item').css('cursor', 'pointer');

    // ---- Lead Type Filter ----
$('.status-toggle .toggle-option').click(function() {
    var lead_type = $(this).data('status').toLowerCase(); // hot/warm/cold
    $('#lead_type').val([lead_type]).trigger('change'); 
    //alert(lead_type);

    // Update active class
    $('.status-toggle .toggle-option').removeClass('active');
    $(this).addClass('active');

    updateTableWithData();
});


    // ---- Lead Status Filter ----
$('.leadStatusbox').on('click', '.lead-status-item', function () {
    var lead_status = $(this).data('lead-status');
    console.log("Clicked lead_status:", lead_status);

    // Clear old selection and set new one
    $('#lead_status').val([lead_status]).trigger('change'); 

    updateTableWithData();
});

});
</script>



<script>
$(document).ready(function() {
    // Remove any previously attached event handlers
    
// function updateTableWithData(response) {
//     // Assuming statusData has a property 'leads' containing the new leads
//     var newLeads = response.leads;
//     var viewOnLeads = response.view_on_leads;
//     var arrLeadStatusRekeyed = response.arrLeadStatusRekeyed;
//     var users = response.users;

//     var dataTable = $('#ticket').DataTable();

//     // Clear existing content of the table body
//     dataTable.clear().draw();
//     // Iterate through new leads and populate the table
//     $.each(newLeads, function (key, lead) {
//         var tr = $('<tr>');
//                         // Determine the inline style for background color based on lead_type
//                         var bgColor = '';
//         if (lead.lead_type === 'hot') {
//             bgColor = 'background-color: red; color: white;';
//         } else if (lead.lead_type === 'warm') {
//             bgColor = 'background-color: yellow; color: black;';
//         } else if (lead.lead_type === 'cold') {
//             bgColor = 'background-color: blue; color: white;';
//         }

//         // Add lead ID column with the inline style for background color
//         tr.append('<td style="' + bgColor + '">' + lead.id + '</td>');

//         // Add each view_on_leads column to the row
//         $.each(viewOnLeads, function (index, view) {
//             var property_name = view.column_name;
//             //alert(property_name);
//             var value;

//             if (property_name === 'currency') {
//                 value = Number(lead[property_name]).toLocaleString();
//             } else if (property_name === 'phone_number') {
//                 value = isNumeric(lead[property_name]) ? formatPhoneNumber(lead[property_name]) : '';
//             }       else if (view.data_type === 'date') {
//             value = formatDate(lead[property_name]);
//         }else {
//                             value = lead[property_name] || '';
//                         }

//             var td = $('<td>').attr('style', (view.label_title_url !== 'email') ? 'text-transform: capitalize;' : '').text(value);
//             tr.append(td);
//         });

//         tr.append('<td>' + (arrLeadStatusRekeyed[lead.lead_status] ? '<span class="right badge" style="background:' + arrLeadStatusRekeyed[lead.lead_status].color_code + ';color:#fff">' + arrLeadStatusRekeyed[lead.lead_status].title + '</span>' : '') + '</td>');
//         tr.append('<td>' + formatDate(lead.created_at ? lead.created_at : '') + '</td>');
//         tr.append('<td>' + formatDate(lead.updated_at ? lead.updated_at : '') + '</td>');
//         tr.append('<td style="text-transform: capitalize;">' + (users[lead.assigned_to] ? users[lead.assigned_to].first_name + ' ' + users[lead.assigned_to].last_name : '') + '</td>');

//         @if(Session::get("level") > 5)
//             tr.append('<td style="text-transform: capitalize;">' + (users[lead.created_by] ? users[lead.created_by].first_name + ' ' + users[lead.created_by].last_name : '') + '</td>');
//         @endif

//         tr.append('<td class="text-center"><div class="list-icons d-inline-flex"><a type="button" href="/leads/' + lead.id + '/edit" class="list-icons-item me-10"><i class="fa fa-edit fa-lg"></i></a><a type="button" href="/leads/view?id=' + lead.id + '" class="list-icons-item me-10"><i class="fa fa-eye fa-lg"></i></a>@if(Session::get("level") > 5)<a type="button" href="#" class="list-icons-item me-10 openLeadDelete" data-id="' + lead.id + '"><i class="fa fa-trash-o fa-lg"></i></a>@endif</div></td>');

//         // Append the new row to the table body
//  dataTable.row.add(tr).draw(false);    });

   
// }

    
});
function formatPhoneNumber(phone) {
    // Remove non-numeric characters from the phone number
    const numericPhone = phone.replace(/\D/g, '');

    // Check if the numeric phone number has 10 digits
    if (numericPhone.length === 10) {
        // Format the phone number as (XXX) XXX-XXXX
        return `(${numericPhone.slice(0, 3)}) ${numericPhone.slice(3, 6)}-${numericPhone.slice(6)}`;
    } else {
        // Return the original phone number if it doesn't have 10 digits
        return phone;
    }
  }
function isNumeric(value) {
    return !isNaN(parseFloat(value)) && isFinite(value);
}
function formatDate(dateStr) {
                  if (!dateStr || dateStr === '0000-00-00') return '';
    var date = new Date(dateStr);
    var month = ('0' + (date.getMonth() + 1)).slice(-2);
    var day = ('0' + date.getDate()).slice(-2);
    var year = date.getFullYear();
    return month + '/' + day + '/' + year;
}

     

</script>


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

    $('#daterange-btn').daterangepicker({
    ranges: {
                        'Today': [moment(), moment()],
                        'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                        'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                        'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                        'This Month': [moment().startOf('month'), moment().endOf('month')],
                        'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
                    },
                    startDate: moment(),
                    endDate: moment()
                }, function (start, end) {
        $('#start_date').val(start.format('YYYY-MM-DD'));
        $('#end_date').val(end.format('YYYY-MM-DD'));
        $('#daterange-btn').val(start.format('MM/DD/YYYY') + ' - ' + end.format('MM/DD/YYYY'));

        // Fetch chart data based on selected date range
        fetchLeadStatusChart(start.format('YYYY-MM-DD'), end.format('YYYY-MM-DD'));
    });

    if (startDate && endDate) {
        $('#daterange-btn').data('daterangepicker').setStartDate(startDate);
        $('#daterange-btn').data('daterangepicker').setEndDate(endDate);
        $('#daterange-btn').val(startDate + ' - ' + endDate);
    } else {
        $('#daterange-btn').val('');
    }
});

// Function to fetch filtered lead status data
function fetchLeadStatusChart(startDate, endDate) {
     $('#loader').show(); // show loader
    $.ajax({
        url: "{{ route('lead-status.chart') }}", // your route to get filtered data
        method: "GET",
        data: { start_date: startDate, end_date: endDate },
        success: function(res) {
    console.log(res);
    $('#loader').hide();

    // Pass the correct arrays from res.data
    updateChart(res.data.filteredLeadStatus, res.data.leadStatusCount);
},

        error: function(err) {
            console.error("Error fetching lead status chart:", err);
              updateChart([], []); // show empty data
                               $('#loader').hide(); // show loader


        }
    });
}

let leadChart = null; // make sure this is global
function updateChart(filteredLeadStatus, leadStatusCount) {
    const legendContainer = document.getElementById("customLegend");
    const noDataMsg = document.getElementById("noDataMsg");
    legendContainer.innerHTML = ""; // clear legend

    const ctx = document.getElementById("cardsChart").getContext("2d");

    // Destroy old chart
    if (leadChart) {
        leadChart.destroy();
        leadChart = null;
        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
    }

    // ✅ If no data
    const chartContainer = document.getElementById("cardsChart").parentElement;

if (!filteredLeadStatus.length || !leadStatusCount.length) {
    chartContainer.style.display = "none";
    noDataMsg.style.display = "block";
    return;
} else {
    chartContainer.style.display = "block";
    noDataMsg.style.display = "none";
}

    // if (!filteredLeadStatus.length || !leadStatusCount.length) {
    //     noDataMsg.style.display = "block";   // show text outside
    //     return; // exit early, no chart
    // } else {
    //     noDataMsg.style.display = "none";    // hide message if data exists
    // }

    const labels = filteredLeadStatus.map(item => item.title);
    const colors = filteredLeadStatus.map(item => item.color_code);
    const chartData = filteredLeadStatus.map(item => {
        const match = leadStatusCount.find(c => c.lead_status === item.lead_title_url);
        return match ? match.total_lead_status : 0;
    });

    const total = chartData.reduce((a, b) => a + b, 0);
    //const totalStatuses = chartData.filter(v => v > 0).length;
    const totalStatuses = @json($record_count);

    const centerTextPlugin = {
        id: 'centerText',
        afterDraw(chart) {
            const { width, height, ctx } = chart;
            ctx.save();
            ctx.font = "bold 14px Arial";
            ctx.fillStyle = "#6B7280";
            ctx.textAlign = "center";
            ctx.textBaseline = "middle";
            ctx.fillText("Total Leads", width / 2, height / 2 - 12);
            ctx.font = "bold 20px Arial";
            ctx.fillStyle = "#111827";
            ctx.fillText(totalStatuses, width / 2, height / 2 + 12);
            ctx.restore();
        }
    };

    leadChart = new Chart(ctx, {
        type: "doughnut",
        data: {
            labels: labels,
            datasets: [{
                data: chartData,
                backgroundColor: colors,
                borderWidth: 0
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            cutout: "70%",
            plugins: {
                legend: { display: false },
                tooltip: {
                    backgroundColor: "#111827",
                    titleColor: "#fff",
                    bodyColor: "#fff",
                    cornerRadius: 6,
                    padding: 10,
                    callbacks: {
                        title: () => '',
                        label: function(context) {
                            const idx = context.dataIndex;
                            const val = context.dataset.data[idx];
                            const pct = total > 0 ? ((val / total) * 100).toFixed(1) : 0;
                            return `${labels[idx]}: ${val} (${pct}%)`;
                        }
                    }
                }
            }
        },
        plugins: [centerTextPlugin]
    });

    // Build legend
    labels.forEach((label, index) => {
        const value = chartData[index];
        const pct = total > 0 ? ((value / total) * 100).toFixed(1) : 0;
        const item = document.createElement("div");
        item.style.display = "flex";
        item.style.alignItems = "center";
        item.style.marginBottom = "6px";
        item.style.whiteSpace = "nowrap";
        item.innerHTML = `
            <span style="display:inline-block;width:16px;height:16px;background:${colors[index]};margin-right:8px;"></span>
            <span style="font-size:14px;font-weight:500;">${label}: ${value} (${pct}%)</span>
        `;
        legendContainer.appendChild(item);
    });
}





</script>

<script src="https://cdn.jsdelivr.net/npm/imask"></script>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        // Get the phone number input
        var phoneInput = document.getElementById('phone_number');

        // Create an IMask instance with the desired mask
        var phoneMask = new IMask(phoneInput, {
            mask: '(000) 000-0000'
        });

        // Add a submit event listener to set the unmasked value before form submission
        document.querySelector('form').addEventListener('submit', function () {
            // Get the unmasked value
            var unmaskedValue = phoneMask.unmaskedValue;

            // Set the unmasked value to the actual input field
            phoneInput.value = unmaskedValue;
        });
    });
</script>
<script>
       $(document).on("click", ".openLeadDelete", function () {
    // Ensure the click event is binding correctly to the dynamically added element
    var delete_id = $(this).data('id');
    $("#delete").modal('show');
    $("#lead_id").val(delete_id);
});

$(document).on("click", ".deleteLead", function () {
    var lead_id = $('#lead_id').val();
    $.ajax({
        url: 'deleteLead/' + lead_id,
        type: 'get',
        success: function (response) {
            window.location.reload(1);
        },
        error: function (xhr, status, error) {
            console.log("Error: " + error);
        }
    });
});

    </script>
<script>
function resetFilter() {
    // Remove query parameters from the URL before refreshing
    history.replaceState(null, null, window.location.pathname);

    // Refresh the page
    location.reload();
}
</script>

<script>
document.querySelectorAll('.toggle-option').forEach(option => {
    option.addEventListener('click', () => {
        document.querySelectorAll('.toggle-option').forEach(opt => opt.classList.remove('active'));
        option.classList.add('active');
    });
});
</script>


 


<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
  const dailyCtx = document.getElementById('dailyChart').getContext('2d');
  new Chart(dailyCtx, {
    data: {
      labels: ['27 Jun','02 Jul','03 Jul','10 Jul','11 Jul','13 Jul','14 Jul','15 Jul','22 Jul','23 Jul'],
      datasets: [
        {
          type: 'bar',
          label: 'Calls Analyzed',
          data: [2, 1, 7, 1, 3, 8, 12, 3, 1, 1],
          backgroundColor: '#ff0000',
          borderRadius: 6
        },
        {
          type: 'line',
          label: 'Avg Lead Score (%)',
          data: [70, 20, 45, 40, 15, 10, 33, 23, 74, 76],
          borderColor: '#2563eb',
          backgroundColor: '#2563eb',
          borderWidth: 2,
          tension: 0.4,
          pointRadius: 4,
          pointBackgroundColor: '#2563eb'
        }
      ]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          position: 'bottom',
          labels: {
            font: {
              size: 14,
              weight: '500',
              family: 'Arial, sans-serif'
            },
            color: '#333',
            padding: 12
          }
        }
      },
      scales: {
        x: {
          ticks: {
            font: {
              size: 14,
              weight: '500',
              family: 'Arial, sans-serif'
            },
            color: '#333',
            padding: 6,
            maxRotation: 0,
            autoSkip: false
          },
          grid: {
            display: true,
            drawTicks: true,
            color: 'rgba(0,0,0,0.1)'
          }
        },
        y: {
          beginAtZero: true,
          title: {
            display: true,
            text: 'Volume / Score',
            font: {
              size: 14,
              weight: '500',
              family: 'Arial, sans-serif'
            },
            color: '#333'
          },
          min: 0,
          max: 80,
          grid: {
            color: 'rgba(0,0,0,0.1)'
          },
          ticks: {
            font: {
              size: 14,
              weight: '500',
              family: 'Arial, sans-serif'
            },
            color: '#333',
            padding: 4
          }
        }
      }
    }
  });
</script>





<script>
  const ctx = document.getElementById("cardsChart").getContext("2d");
  const leadStatusList = @json($filteredLeadStatus);
  const leadStatusCount = @json($lead_status_count['leadstatus']);

  const labels = leadStatusList.map(item => item.title);
  const colors = leadStatusList.map(item => item.color_code);

  // prepare chart data dynamically
  const chartData = leadStatusList.map(item => {
    const match = leadStatusCount.find(c => c.lead_status === item.lead_title_url);
    return match ? match.total_lead_status : 0;
  });

  // total for percentage calculations
  const total = chartData.reduce((a, b) => a + b, 0);
  // plugin to draw text in center

  // ✅ total lead statuses (categories)
  // const totalStatuses = chartData.filter(v => v > 0).length;
  const totalStatuses = @json($record_count);

  // plugin to draw text in center
  const centerTextPlugin = {
    id: 'centerText',
    afterDraw(chart) {
      const { width, height, ctx } = chart;
      ctx.save();

      // Label
      ctx.font = "bold 14px Arial";
      ctx.fillStyle = "#6B7280";
      ctx.textAlign = "center";
      ctx.textBaseline = "middle";
      ctx.fillText("Total Leads", width / 2, height / 2 - 12);

      // Value (show count of lead statuses)
      ctx.font = "bold 20px Arial";
      ctx.fillStyle = "#111827";
      ctx.fillText(totalStatuses, width / 2, height / 2 + 12);

      ctx.restore();
    }
  };
  new Chart(ctx, {
    type: "doughnut",
    data: {
      labels: labels,
      datasets: [{
        data: chartData,
        backgroundColor: colors,
        borderWidth: 0
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      cutout: "70%",
      plugins: {
        legend: { display: false },
        tooltip: {
          backgroundColor: "#111827",
          titleColor: "#fff",
          bodyColor: "#fff",
          cornerRadius: 6,
          padding: 10,
          callbacks: {
            title: function() { return ''; },
            label: function (context) {
              const index = context.dataIndex;
              const label = context.chart.data.labels[index];
              const value = context.dataset.data[index];
              const percentage = total > 0 ? ((value / total) * 100).toFixed(1) : 0;
              return `${label}: ${value} (${percentage}%)`;
            }
          }
        }
      }
    },
      plugins: [centerTextPlugin] // add plugin here
  });

  // Custom legend with values and percentages
  const legendContainer = document.getElementById("customLegend");
  legendContainer.innerHTML = ""; // clear legend

labels.forEach((label, index) => {
    const value = chartData[index];
    const percentage = total > 0 ? ((value / total) * 100).toFixed(1) : 0;

    const item = document.createElement("div");
    item.style.display = "flex";       // horizontal alignment for color + text
    item.style.alignItems = "center";
    item.style.marginBottom = "6px";    // spacing between items
    item.style.whiteSpace = "nowrap";   // prevent text wrapping within a row
    item.innerHTML = `
        <span style="display:inline-block; width:16px; height:16px; background:${colors[index]}; margin-right:8px;"></span>
        <span style="font-size:14px; font-weight:500;">${label}: ${value} (${percentage}%)</span>
    `;
    legendContainer.appendChild(item);
});


  // labels.forEach((label, index) => {
  //   const value = chartData[index];
  //   const percentage = total > 0 ? ((value / total) * 100).toFixed(1) : 0;
  //   const item = document.createElement("div");
  //   item.style.display = "flex";
  //   item.style.alignItems = "center";
  //   item.style.marginBottom = "6px";
  //    item.style.whiteSpace = "nowrap"; // prevent line breaks
  //   item.innerHTML = `
  //     <span style="display:inline-block; width:16px; height:16px; background:${colors[index]}; margin-right:8px;"></span>
  //     <span style="font-size:14px; font-weight:500;">${label}: ${value} (${percentage}%)</span>
  //   `;
  //   legendContainer.appendChild(item);
  // });
</script>

@endsection