@extends('layouts.app')
@section('title', 'Lead Lists')
@section('content')

<style>
  .table > thead > tr > td, .table > thead > tr > th {
    padding: 0.4rem;
    vertical-align: middle;
}

  </style>
  <?php

error_reporting(0);

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)) . " - 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');
    }
?>
<section class="content">
  <div class="row">       
    <div class="col-lg-12 col-12">
      <div class="box">
                        
          <div class="box-body"><!--bg-lightest-->
            <div class="text-end">
            <h4 class="box-title text-info mb-0"style="float:left;"id="show"><i class="icon-Add-user"><span class="path1"></span><span class="path2"></span></i> Leads</h4>



            <a href="{{url('/leads/add')}}" type="button" style="float:right" class="waves-effect waves-light btn btn-rounded btn-primary btn-sm"><i class="fa fa-plus fa-sx"></i> Add Lead</a>
            <!-- Categroy 1 -->
            <a id="msg"style="display:none;color:green;margin-right:5px;">Affiliate Link Copied !!</a>
            <?php
     if ($crm_system && $crm_system[0]->company_domain) {
         $domainName = $crm_system[0]->company_domain;
     } else {
         // Assuming you have already set the DOMAIN_NAME environment variable
         $domainName = getenv('DOMAIN_NAME');
     }
 ?>
 
                <a  
   id="affiliateLink" 
   style="margin-right:5px;" 
   class="waves-effect waves-light btn btn-rounded btn-primary btn-sm" 
   onclick="copyToClipboard('<?php echo $domainName; ?>/affiliate/customer/user/app/index{{Session::get('affilaite_link_token')}}')">
  <i class="fa fa-user fa-lg" aria-hidden="true"></i> Affiliate Link
</a>

            <a  style="margin-right:5px;"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> Search
                </a>

           </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">
                        <form method="post">
                          @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="col-md-3">
                                <div class="form-group">
                                    <label class="form-label">CRM ID</label>
                                    <input class="form-control " value="{{request()->input('crm_id')}}" name="crm_id" id="crm_id" placeholder="CRM ID">
                                </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">
                                </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)
                                                            <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>
                                                                
                                                        @endforeach
                                                    @endif

                                                    @else
                                                    <option
                                                                value="{{Session::get("userId")}}">{{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="reservation">
                      <input type="hidden" id="start_date" name="start_date" value="{{ $startDate }}">
                      <input type="hidden" id="end_date" name="end_date" value="{{ $endDate }}">                              
                      </div>
                          </div>
                            <div class="box-footer text-end">
        

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

                <button  type="submit" name="submit" value="add" class="btn btn-primary">
                  <i class="ti-save-alt"></i> Submit
                </button>
              </div>    
  </form>
                          </div>
                        </div>
                      </div>
                    </div>
                  <!-- End Question 1 -->										
                </div>
					  
                
                <div class="row">
                  <h4 class="box-title text-info mb-0"style="display:none;"id="hide"><i class="icon-Add-user"><span class="path1"></span><span class="path2"></span></i> Leads</h4>
                  <hr class="my-15">

<div class="table-responsive">
                <table id="tickets1" class="table mt-0 table-hover no-wrap" data-page-size="10">
                  <thead>
                            <tr>
                              <th>#</th>
                         @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)
                    {

                        if($lead->lead_parent_id != '0')
                        {



                        ?>
                        <tr>
                            <?php
                            if( $lead->lead_type == 'hot')
                            {
                                $style ="background-color:#a90329!important;color:#fff;text-align:center;";
                            }
                            else if( $lead->lead_type == 'warm')
                            {
                                $style ="background-color:#c79121!important;color:#fff;text-align:center;";
                            } 
                            else if( $lead->lead_type == 'cold')
                            {
                                $style ="background-color:#12679b!important;color:#fff;text-align:center;";
                            }
                            else
                            {
                                $style="text-align:center;";
                            } 
                            

                           // $style="";

                            
                        ?>

                        <td>{{$lead->id}}</td>
                        @if(!empty($view_on_leads))
                            @foreach($view_on_leads as $view)
                            @php
                                $property_name = $view->column_name;
                                if($view->column_name == '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->column_name == 'phone_number')
                                if(is_numeric($lead->$property_name))
                                $value = \App\Helper\Helper::phone_number($lead->$property_name) ;
                                else
                                $value='-';
                                else
                                $value = $lead->$property_name;
                  
                            @endphp
                        <td @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>{{ \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>{{date('m/d/Y H:i',strtotime($lead->created_at))}}</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 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>
           
            
                       </div>
                
              </div>
              <!-- /.box-body -->
          
            <!-- /.box -->      
        					
            <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>	
            
    </div>

  </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>
      $(".openLeadDelete").click(function () {
            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);
                }
            });
        });

 $(document).ready(function() {
  $('#reservation').daterangepicker({
    locale: { format: 'MM/DD/YYYY' },
    "startDate": "{{ \App\Helper\Helper::formatDateMMDDYYYY($startDate) }}",
    "endDate": "{{ \App\Helper\Helper::formatDateMMDDYYYY($endDate) }}",
    opens: 'right'
}, function(start, end, label) {
    console.log('New date range selected: ' + start.format('MM/DD/YYYY') + ' to ' + end.format('MM/DD/YYYY') + ' (predefined range: ' + label + ')');
    $("#start_date").val(start.format('MM-DD-YYYY'));
    $("#end_date").val(end.format('MM/DD/YYYY'));
});
    // Check if start date and end date are empty, if so, clear the input fields
    if ("{{ $startDate }}" === '') {
        $("#start_date").val('');
    }

    if ("{{ $endDate }}" === '') {
        $("#end_date").val('');
    }
});

$(document).ready(function() {
    $('#tickets1').DataTable({
        order: [[0, 'desc']],

        columnDefs: [
            {
                targets: [2, 3, 4, 5,7,8,9,10], // Columns to disable sorting
                orderable: false
            },
            {
                targets: [1,6], // Name column, enable sorting
                orderable: true
            }
        ]
    });
});
</script>

<script>
document.addEventListener('DOMContentLoaded', function () {
    var searchButton = document.querySelector('.btn-bitbucket');
    var collapseElement = new bootstrap.Collapse(document.getElementById('answer-1'), { toggle: false });
    var leadsHeading = document.getElementById('hide');
    var leadsHeadingShow = document.getElementById('show');

    // Function to check the conditions for opening the form
    function shouldOpenForm() {
        // Check the specified conditions
        return (
            {!! json_encode(
                !empty(request()->input('lead_status')) || 
                !empty(request()->input('assigned_to')) || 
                !empty(request()->input('first_name')) || 
                !empty(request()->input('last_name')) || 
                !empty(request()->input('email')) || 
                !empty(request()->input('legal_company_name')) || 
                !empty(request()->input('lead_type')) ||
                !empty(request()->input('phone_number')) ||
                !empty(request()->input('start_date')) ||
                !empty(request()->input('end_date'))
            ) !!}
        );
    }

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

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

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

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

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

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

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


<script>
function copyToClipboard(textToCopy) {
  // Create a temporary textarea element
  var textarea = document.createElement('textarea');
  textarea.value = textToCopy;
  document.body.appendChild(textarea);

  // Select and copy the text
  textarea.select();
  document.execCommand('copy');

  // Remove the temporary textarea
  document.body.removeChild(textarea);

  // Show the message in the 'msg' element
  var msgElement = document.getElementById('msg');
  msgElement.style.display = 'inline'; // Make the element visible
  setTimeout(function() {
    msgElement.style.display = 'none'; // Hide the element after a delay (e.g., 3 seconds)
  }, 3000); // Adjust the delay in milliseconds (3 seconds in this example)
}
</script>


@endpush

@endsection

