@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);
$startDate = request()->input('start_date') ?? '';
$endDate = request()->input('end_date') ?? '';
// if (!empty(request()->input('start_date')))
//     {
//         $startDate = request()->input('start_date');
//     }
//     else
//     {
//         $current_date = date("Y-m-d"); 
//         //$str_date = strtotime(date("Y-m-d"));//, strtotime($current_date)) . " - day");
//         $str_date = strtotime(date("Y-m-d", strtotime($current_date)) . " -90 day");
//         $startDate = date('Y-m-d', $str_date);

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

@if(Session::get('parentId') == 3 || Session::get('parentId') == 11)
<a class="waves-effect waves-light btn btn-rounded btn-primary btn-sm"  href="/pdf-reader-setting" type="submit"class="dropdown-item" href="#"> Pdf Setting </a>


<a class="waves-effect waves-light btn btn-rounded btn-primary btn-sm"  id="openExcelForm" type="submit"class="dropdown-item" href="#">Upload Pdf </a>
@endif

            <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> Filter
                </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">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="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="resetFilter();" 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)
                    {



                        ?>
                        <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;
            $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>
                                      
                                      @if(!in_array($lead->id, $merchants))
                                        <a title="Create Merchant Account" data-id="{{$lead->id}}" data-email="{{$lead->email}}"  style="cursor:pointer;" type="button" href="#" class="list-icons-item me-10 create-cred" id="create-cred-{{$lead->id}}" >
                                          <i class="fa fa-book fa-lg"></i>
                                        </a>
                                      @endif

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

   <div class="modal fade" id="myModalExcel" tabindex="-1" aria-labelledby="myModalExcelLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"  id="upload-excel"></h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>

      <form method="post" action="{{url('pdf/uploadDid')}}" enctype="multipart/form-data">
      <!-- <form id="uploadForm"method="post" action="{{url('pdf/uploadDid')}}" enctype="multipart/form-data"> -->
      @csrf
      <div class="modal-body">
      <div id="loader" style="display: none;">
                    <img src="{{ asset('assets/images/giphy.gif') }}" alt="Loading..."style="height:100px;width:100px;">
                </div>
                <input type="hidden" class="form-control" name="did" value="" >
                <label for="inputEmail3" class="form-label closed">PDF</label>
                    <input type="file" accept=".pdf" class="form-control closed" required name="did_file" id="did_file" placeholder="Select PDF File">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Close</button>
        <button type="submit"name="submit" class="btn btn-info btn-sm ">Upload</button>
      </div>
        </form>
    </div>
  </div>
</div>

  @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>
    var parentId = "{{Session::get('parentId')}}";

$("#openExcelForm").click(function() {
console.log('did_file');
$("#myModalExcel").modal('show');
$("#name").val('');
$("#status").val('1');
$("#id").val('');
$(".closed").show();
$("#upload-excel").html('Upload PDF');


});
      $(".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).on("click", ".create-cred", function () {
        var email = $(this).data('email');
        var clientId = parentId;
        var leadId = $(this).data('id');

        $.ajax({
            url: 'merchant-add',
            type: 'POST',
            data: {
                "email": email,
                "client_id": clientId,
                "lead_id": leadId
            },
            success: function (response) {
              if (response.success == false) {                
                $.each(response.errors, function(key,valueObj){
                  toastr.error(valueObj[0]);
                });                
              } else {
                $("#create-cred-" + leadId).hide();
                toastr.success(response.message)
              }
            }
        });
      });
        
//  $(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>
<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 type="text/javascript">
        $(function () {
            var startDate = "{{ $startDate }}";
            var endDate = "{{ $endDate }}";

            // Log the startDate and endDate for debugging purposes
            console.log("Start Date: ", startDate);
            console.log("End Date: ", endDate);

            $('#reservation').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'));
                $('#reservation').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) {
                $('#reservation').data('daterangepicker').setStartDate(startDate);
                $('#reservation').data('daterangepicker').setEndDate(endDate);
                $('#reservation').val(startDate + ' - ' + endDate);
            } else {
                $('#reservation').val(''); // Ensure the input field is empty initially
            }
        });
    </script>
    <script>
    $(document).ready(function () {
    $('#uploadForm').submit(function (e) {
        e.preventDefault(); // Prevent the default form submission

        // Show the loader
        $('#loader').show();
        var fileInput = $('#did_file')[0]; // Get the file input element
        var file = fileInput.files[0]; // Get the selected file

        // Check if a file was selected and if it's a PDF
        if (file) {
            var fileType = file.type; // Get the file MIME type

            // Check if the file is a PDF (MIME type: application/pdf)
            if (fileType !== 'application/pdf') {
                toastr.error('Please upload a valid PDF file.');
                 // Close the modal
                $('#uploadForm')[0].reset();
                $('#loader').hide(); // Hide the loader
                return; // Stop the form submission
            }
        } else {
          toastr.error('Please select a file to upload.');
            $('#loader').hide(); // Hide the loader
            return; // Stop the form submission
        }
        var formData = new FormData(this); // Get form data (including the file)

        $.ajax({
            url: '{{url('pdf/uploadDid')}}', // Form action URL
            type: 'POST',
            data: formData,
            contentType: false, // Don't set content-type header
            processData: false, // Don't process the data (it needs to be sent as FormData)
            success: function (response) {
                // Hide the loader
                $('#loader').hide();                
                $('#myModalExcel').modal('hide'); // Assuming the modal has the id 'uploadModal'
                // Handle success (you can display a success message or update the UI)
                toastr.success('File uploaded successfully!');
                console.log(response); // Log the response (you can use it to show any additional message)
                // Optionally, reset the form here
                $('#uploadForm')[0].reset();
            },
            error: function (xhr, status, error) {
                // Hide the loader
                $('#loader').hide();

                // Handle error (you can display an error message)
                alert('An error occurred while uploading the file.');
                console.log(xhr.responseText); // Log the 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>


@endpush

@endsection

