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

<style>
  .table > thead > tr > td, .table > thead > tr > th {
    padding: 0.4rem;
    vertical-align: middle;
}
/* Custom style for pagination links */
    .pagination {
        margin: 0; /* Remove default margin */
        padding: 0; /* Remove default padding */
        list-style: none; /* Remove list bullet points */
        display: flex; /* Use flex layout for horizontal alignment */
    }

    .pagination li a {
        padding:6px;
    }

    .pagination a {
        display: inline-block;
        padding: 0; /* Adjust the padding as needed */
        text-decoration: none;
        background-color: #f0f0f0;
        border: 1px solid #ccc;
        color: #333;
        transition: background-color 0.3s ease, color 0.3s ease;
    }

    .pagination a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .pagination .active a {
        background-color: #007bff;
        color: #fff;
    }

  </style>
  <?php

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');
    }
?>
  <?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();
        ?>
<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">
       <!-- <b>Total Rows :<?= $record_count ?></b>        -->
               
<div class="table-responsive">
        <table class="table mt-0 table-hover no-wrap" id="myTable">
                                <thead id="tableHeaderRow">

                                </thead>

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

                                <tbody>

                                </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>
            $(document).ready(function() {
                $.ajax({
                    url: '/sub-leads', // your route here
                    type: 'GET',
                    dataType: 'json',
                    success: function(response) {
                    
                        let columns = [];

                        columns.push({
                            data: 'id',
                            title: '#',
                            orderable: false,
                            searchable: false,
                            render: function(data) {
                                return data; // render raw HTML
                            }
                        });



                        // Add dynamic columns from lead_view
                        $.each(response.lead_view, function(i, col) {
                            console.log(col.title);
                            columns.push({
                                data: col.column_name,
                                title: col.title,
                                render: function(data, type, row) {
                                    if (col.data_type === 'currency' && data !== null) {
                                        return parseFloat(data).toLocaleString(
                                            undefined, {
                                                minimumFractionDigits: 2
                                            });
                                    } else if (col.data_type === 'date' && data) {
                                        let date = new Date(data);
                                        return date.toLocaleDateString() + ' ' + date
                                            .toLocaleTimeString();
                                    } else if (col.data_type === 'phone_number' &&
                                        data) {
                                        // Add phone formatting if needed
                                        return data;
                                    }
                                    return data !== null ? data : '';
                                }
                            });
                        });


                        // Status column (contains HTML badges)
                        columns.push({
                            data: 'lead_status',
                            title: 'Status',
                            orderable: false,
                            searchable: false,
                            render: function(data) {
                                return data; // render raw HTML
                            }
                        });

                        columns.push({
                            data: 'lead_parent_id',
                            title: 'Sub Lead',
                            render: function(data, type, row) {
                                if (data !== '0' && data !== 0 && data !== null) {
                                    return 'Sub Lead of MID- <a href="/leads/view?id=' + data +
                                        '">' + data + '</a>';
                                }
                                return '';
                            }
                        });
                        columns.push({
                            data: 'created_at',
                            title: 'Created',
                            orderable: false,
                            searchable: false,
                            render: function(data) {
                                return data; // render raw HTML
                            }
                        });
                        columns.push({
                            data: 'updated_at',
                            title: 'Modified',
                            orderable: false,
                            searchable: false,
                            render: function(data) {
                                return data; // render raw HTML
                            }
                        });


                        columns.push({
                            data: 'assigned_to_user',
                            title: 'assigned_to',
                            orderable: false,
                            searchable: false,
                            render: function(data) {
                                return data; // render raw HTML
                            }
                        });

                        @if (Session::get('level') > 5)
                            columns.push({
                                data: 'created_by_user', // Adjust this to your actual data field
                                title: 'Created By',
                            });
                        @endif
                        // Action column (buttons)
                        columns.push({
                            data: 'action',
                            title: 'Action',
                            orderable: false,
                            searchable: false,
                            render: function(data) {
                                return data; // render raw HTML
                            }
                        });
                        $('#myTable').DataTable({
                             order: [], // disable initial ordering
                            processing: true,
                            serverSide: false,
                            data: response.data,
                            columns: columns,
                            responsive: false, // 🔥 disable responsive behavior
                            autoWidth: false, // optional: don't automatically calculate column width
                            scrollX: true, // 🔥 allow horizontal scroll instead of collapsing
                            pageLength: 10
                        });

        


                    },
                    error: function(xhr, status, error) {
                        console.error('Failed to load leads data:', error);
                    }
                });

                // $('#myTable').on('click', '.openLeadDelete', function() {
                //     var delete_id = $(this).data('id');
                //     $("#delete").modal('show');
                //     $("#lead_id").val(delete_id);
                // });
            });
        </script>
    <script>
             $('#myTable').on('click', '.openLeadDelete', 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('');
    }
});


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

