
@extends('layouts.app')
@section('title', 'Dashboard')
@section('content')
<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>
<section class="content">
<?php

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

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

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

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

            $perPage = $show;
            $paginator = new Illuminate\Pagination\LengthAwarePaginator($leads, $record_count ,$perPage,$currentPage,['path' => url($url)]);
            $record_count = $paginator->total();
        ?>
<div class="row">
        <div class="col-xl-12 col-12">


<div class="row leadStatusbox">
 <div class="row leadStatusbox">
    @foreach ($filteredLeadStatus as $leadStatus)
   @php
    $leadStatusUrl = $leadStatus->lead_title_url;

    // Filter matching counts (using object property access)
    $matchingCounts = array_filter($lead_status_count['leadstatus'] ?? [], function ($countItem) use ($leadStatusUrl) {
        return isset($countItem->lead_status) && $countItem->lead_status === $leadStatusUrl;
    });

    // Sum up totalLeadStatus
    $totalLeadStatus = array_reduce($matchingCounts, function ($sum, $item) {
        return $sum + ($item->total_lead_status ?? 0);
    }, 0);

    $bgColor = $leadStatus->color_code ?? 'green';
@endphp


<div class="col-lg-3 col-12 lead-status-item"
     style="width: 20%; cursor: pointer;"
     onclick="window.location.href='{{ url('crm-dashboard-new') }}?status={{ $leadStatus->lead_title_url }}'">
            <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 0;font-size: 13px;">
                                {{ $leadStatus->title }}
                            </h5>
                            <h2 style="color:white;" class="fw-500 mb-0">{{ $totalLeadStatus }}</h2>
                        </div>
                        <div>
                            <i class="icon-Add-user"><span class="path1"></span><span class="path2"></span></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    @endforeach
</div>

</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 class="panel-group panel-group-simple panel-group-continuous mb-0" id="accordion2"
            aria-multiselectable="true" role="tablist">
            <!-- Question 1 -->
            <div class="panel">
              <div id="question-1" role="tab">
             
                      </div>
                      <div class="panel-collapse collapse  " id="answer-1" aria-labelledby="question-1" role="tabpanel" data-bs-parent="#category-1">
                        <div class="panel-body">
                        <form method="post" 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%">
                                          @if(!empty($lead_status))
                                        @foreach($lead_status as $status)
                                            <option @if(empty(request()->input('lead_status'))) @elseif(in_array($status->lead_title_url, request()->input('lead_status'))) selected @endif 
                                            value="{{$status->lead_title_url}}">{{$status->title}}</option>
                                        @endforeach
                                        @endif
                                    </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%">
                                     @if(Session::get("level") > 5)
                                    
                                                    @if(!empty($user))
                                                          @foreach($sortedUsers as $list)
                                                           @if($list->is_deleted == '0' && $list->user_level < 9)
                                                            <option @if(empty(request()->input('assigned_to'))) @elseif(in_array($list->id, request()->input('assigned_to'))) selected @endif 
                                                                value="{{$list->id}}">{{ucwords($list->first_name)}} {{ucwords($list->last_name)}}</option>
                                                    @endif
                                                                
                                                                
                                                        @endforeach
                                                    @endif

                                                    @else
                                                    <option
                                                                value="{{Session::get("id")}}">{{Session::get("first_name")}} {{Session::get("last_name")}}</option>

                                                    @endif
                                    </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 class="d-flex justify-content-center">
    <button class="btn btn-danger mx-2 filter-btn" data-filter="hot" onclick="window.location.href='{{ url('crm-dashboard-new') }}?lead_type=hot'">Hot</button>
    <button class="btn btn-yellow mx-2 filter-btn" data-filter="warm" onclick="window.location.href='{{ url('crm-dashboard-new') }}?lead_type=warm'">Warm</button>
    <button class="btn btn-primary mx-2 filter-btn" data-filter="cold" onclick="window.location.href='{{ url('crm-dashboard-new') }}?lead_type=cold'">Cold</button>
</div>


            <div class="col-xl-12 col-12">
                <b>Total Rows :<?= $record_count ?></b>       
                    <form method="GET" action="">
                    <div style="text-align:right;">
                    <label class="form-label"style="margin-top:5px;">Search:</label>
                        <input class="form-control form-control-sm"type="search" name="search"id="search" placeholder=""value="{{ $searchTerm }}"style="width:auto;float:right;margin-left:0.5em;display:inline-block;margin:0 10px;padding: 5px 30px 5px 15px;">
                        <!-- <button type="submit"><i class="fa fa-search"></i></button> -->
                        </div>
                    <label class="label-class" for="show">Show:</label>
                        <select class="form-select form-control-sm"name="show" onchange="this.form.submit()"style="width:75px;display:inline-block;">
                            <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">
                  <thead>
                            <tr>
                              <th>#</th>
                         @foreach($view_on_leads as $view)
                        <th>{{$view->title}}</th>
                        @endforeach
                        <th>Status</th>
                        <th>Sub Lead</th>

                        <th>Created</th>
                        <th>Modified</th>
                        <th>Assigned To</th>
                                                    @if(Session::get("level") > 5)

                        <th>Created By</th>
                        @endif
                        <th>Action</th>

                                                
                        

                            </tr>
                  </thead>

                  <?php //echo "<pre>";print_r($leads);die; ?>

                  <tbody>
                    <?php
                    $k = $lower_limit;
                    foreach ($leads as $key => $lead)
                    {



                        ?>
                        <tr>
                            

                        

                            
                    

                        <!-- <td>{{$lead->id}}</td> -->
                         <td 
    @php
        $bgColor = '';
        if ($lead->lead_type === 'hot') {
            $bgColor = 'background-color: red; color: white;';
        } elseif ($lead->lead_type === 'warm') {
            $bgColor = 'background-color: yellow; color: black;';
        } elseif ($lead->lead_type === 'cold') {
            $bgColor = 'background-color: blue; color: white;';
        }
    @endphp
    style="{{ $bgColor }}"
>
    {{$lead->id}}
</td>

                        @if(!empty($view_on_leads))
                            @foreach($view_on_leads as $view)
                            @php
            $property_name = $view->column_name;
            $value = ''; // Default value

            if ($view->data_type == 'currency') {
                $value = number_format($lead->$property_name);
            } elseif ($view->data_type == 'date') {
                $dateValue = $lead->$property_name;
                if (!empty($dateValue) && $dateValue != '0000-00-00') {
                    $value = \App\Helper\Helper::formatDateMMDDYYYY($dateValue);
                } elseif ($dateValue == '0000-00-00') {
                    $value = '';
                }
            } elseif ($view->data_type == 'phone_number') {
                if (is_numeric($lead->$property_name)) {
                    $value = \App\Helper\Helper::phone_number($lead->$property_name);
                }

                else
                if (!is_numeric($lead->$property_name)) {
                    $value = \App\Helper\Helper::phone_number($lead->$property_name);
                }

                 else {
                    $value = '';
                }
            } else {
                $value = $lead->$property_name ?? '';
            }
        @endphp
                        <td style="white-space: nowrap;" @if($view->label_title_url != 'email') style="text-transform: capitalize;" @endif>

                            @if(!empty($value)) {{$value}} @else @endif
                        </td> 
                            @endforeach
                        @endif

                       {{-- <td><span class="right badge" style="{{$style}}">{{strtoupper($lead->lead_type)}}</span></td> --}}
                        
                        <td>@if(isset($lead_status[$lead->lead_status]))<span class="right badge" style="background:{{$lead_status[$lead->lead_status]->color_code}};color:#fff"> {{$lead_status[$lead->lead_status]->title}} </span> @else  @endif</td>
                        <td>@if($lead->lead_parent_id!='0') Sub Lead of MID- <a  href="/leads/view?id={{$lead->lead_parent_id}}">{{$lead->lead_parent_id}}</a> @endif</td>
                        <td>{{ \Carbon\Carbon::parse($lead->created_at)->setTimezone($timezone)->format('m/d/Y H:i A')}}</td> {{--{{\App\Helper\Helper::changeDateFormate($lead->created_at,'M-d-Y h:i:s A')}}--}}
                        <!-- <td>{{date('m/d/Y H:i',strtotime($lead->updated_at))}}</td>{{--{{\App\Helper\Helper::changeDateFormate($lead->updated_at,'M-d-Y h:i:s A')}}--}} -->
                        <td>{{ \Carbon\Carbon::parse($lead->updated_at)->setTimezone($timezone)->format('m/d/Y H:i A')}}</td> {{--{{\App\Helper\Helper::changeDateFormate($lead->created_at,'M-d-Y h:i:s A')}}--}}

                        <td style="text-transform: capitalize;">{{$users[$lead->assigned_to]->first_name}} {{$users[$lead->assigned_to]->last_name}}</td>

                                                    @if(Session::get("level") > 5)


                        <td style="text-transform: capitalize;">{{$users[$lead->created_by]->first_name}} {{$users[$lead->created_by]->last_name}}</td>
                        @endif
                                  
                                  <td class="text-center">
                                    <div class="list-icons d-inline-flex">
                                      <a style="cursor:pointer;" type="button" href="/leads/{{$lead->id}}/edit" class="list-icons-item me-10"><i class="fa fa-edit fa-lg"></i></a>
                                      @if(Session::get("level") > 5)
                                      <a style="cursor:pointer;" href="#" class="list-icons-item me-10 openLeadDelete" data-id="{{$lead->id}}"><i class="fa fa-trash-o fa-lg"></i></a>
                                      @endif
                                      <a  style="cursor:pointer;"type="button" href="/leads/view?id={{$lead->id}}" class="list-icons-item me-10"><i class="fa fa-eye fa-lg"></i></a>
                                      
                                   

                                  </td>
                                </tr>

                              

                                    

                  <?php }?>
                </tbody>
                </table>
              </div>
  <div style="float:right;">
                        {{$paginator->appends(Request::all())->links()}}
                       </div>
<!-- Table placeholder -->

            </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>	

</section>

<script>
$('#downloadExcelButton').on('click', function(e) {
    e.preventDefault(); // Prevent any default form submission

    var form = $('#leadForm1')[0]; // Get the form element
    var formData = $(form).serialize(); // Serialize all form inputs

    var actionUrl = '{{ url("crm-dashboard") }}'; // Adjust this route if needed

    // Append download flag and redirect to download Excel
    window.location.href = actionUrl + '?' + formData + '&submit_download=1';
});

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 }}";

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

        // If both start and end dates are provided, set them in the input field
        if (startDate && endDate) {
            $('#reservation1').data('daterangepicker').setStartDate(startDate);
            $('#reservation1').data('daterangepicker').setEndDate(endDate);
            $('#reservation1').val(startDate + ' - ' + endDate);
        } else {
            $('#reservation1').val(''); // Ensure the input field is empty initially
        }
    });
</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>
@endsection