@extends('layouts.app')

@section('content')
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />
<div class="row">
	<div class="col-lg-12">
		<a class="btn btn-primary btn-xs mb-2" data-title="{{ _lang('Create New Lead') }}" href="{{ route('leads.create') }}"><i class="ti-plus"></i> {{ _lang('Add New') }}</a>
		<a class="btn btn-dark btn-xs mb-2" href="{{ route('leads.import') }}"><i class="ti-upload"></i> {{ _lang('Imports') }}</a>
		 @if (Auth::user()->user_type == 'staff')   
		<!-- <a class="btn btn-secondary btn-xs mb-2" href="{{ url('leads/kanban') }}"><i class="ti-layout-column3"></i> {{ _lang('Kanban View') }}</a> -->
		@endif
		<div class="card mt-2">
		    
			<span class="panel-title d-none">{{ _lang('Lead List') }}</span>
				
			<div class="card-body">
                <div class="row">
                    @if(Auth::user()->user_type == 'user' || Auth::user()->role_id == 17)
                     <div class="col-lg-3">
                     	 <label>{{ _lang('Marketing Person') }}</label>
                     	 <select class="form-control select2 select-filter" name="assigned_user_id">
                             <option value="">{{ _lang('ALL') }}</option>
                             <option value="notassign">{{ _lang('Lead Not Assigned') }}</option>
                             {{ create_option_sales('users','id','name','',array('company_id=' => company_id(), 'user_type=' => 'staff')) }}
                     	 </select>
                     </div>	
                    @endif
                    @if(Auth::user()->user_type == 'user' || Auth::user()->role_id == 17 || Auth::user()->role_id == 8)
                     <div class="col-lg-3">
                     	 <label>{{ _lang('Lead Status') }}</label>
                     	 <select class="form-control select2 select-filter" data-placeholder="{{ _lang('ALL') }}" name="lead_status_id" multiple="true">
							{{ create_option('lead_statuses','id','title','',array('company_id=' => company_id())) }}
                     	 </select>
                     </div>	
                    @endif
                     <div class="col-lg-3">
                     	 <label>{{ _lang('Lead Source') }}</label>
                     	 <select class="form-control select2 select-filter" name="lead_source_id">
                     	 	<option value="">{{ _lang('ALL') }}</option>
							{{ create_option('lead_sources','id','title','',array('company_id=' => company_id())) }}
                     	 </select>
                     </div>	

                     <!-- <div class="col-lg-3">
                     	 <label>{{ _lang('Country') }}</label>
                     	 <select class="form-control select2 select-filter" name="country">
                     	 	<option value="">{{ _lang('ALL') }}</option>
							{{ get_country_list() }}
                     	 </select>
                     </div>	-->
                     <div class="col-lg-3">
                     	 <label>{{ _lang('Timezone') }}</label>
                     	 <select class="form-control select-filter" name="time_zone" id="time_zone">
                     	 	<option value="">{{ _lang('ALL') }}</option>
							@foreach(App\TimeZoneList::all()  as $tiz)
							                     	 	<option value="{{$tiz->id}}">{{ $tiz->name }}</option>

							@endforeach
                     	 </select>
                     </div>	
                      <div class="col-lg-3">
                     	 <label>{{ _lang('state') }}</label>
                     	 <select class="form-control select2 select-filter" name="zone_state" id="zone_state">
                     	 
                     	 </select>
                     </div>	
                    <!-- <div class="col-lg-3">
                     	 <label>{{ _lang('Project Type') }}</label>
                     	 <select class="form-control select2 select-filter" name="project_type">
                     	 	<option value="">{{ _lang('ALL') }}</option>
                     	 	<option value="Mobile">Mobile</option>
                     	 	<option value="SEO">SEO</option>
                     	 	<option value="Web">Web</option>
							
                     	 </select>
                     </div>-->	
                      
                     <div class="col-lg-3">
                     	 <label>{{ _lang('Search By Name') }}</label>
                     	 <input type="text" class="form-control search-filter" name="search">
                     </div>
                     
                     <div class="col-lg-3">
                     	 <label>{{ _lang('Search By Email') }}</label>
                     	 <input type="text" class="form-control search-email" name="email">
                     </div>
                     
                     <div class="col-lg-3">
                     	 <label>{{ _lang('Search By Next FollowUp Date') }}</label>
                     	 <input type="text" class="form-control search-status_date" name="status_date">
                     </div>
                     
                </div>
				<hr>
				@if(Auth::user()->user_type == 'user' || Auth::user()->role_id == 17)
				<div class="row">

					<div class="col-lg-3">
						<label>{{ _lang('Marketing Person') }}</label>
						<select class="form-control select2" id="select2ID" name="assigned_user_id" required>
							<option value="">{{ _lang('ALL') }}</option>
							{{ create_option_sales('users','id','name','',array('company_id=' => company_id(), 'user_type=' => 'staff')) }}
						</select>
					</div>

				<div class="col-lg-3" style="margin-top: 25px!important;">
					<label></label>
				<button type="button" class="btn btn-secondary btn-xs mb-2" id="button">Assign Leads </button>
				</div>
				</div>
                <hr>
				@endif
				<table id="leads_table" class="table table-striped">
					<thead>
					<th>ID</th>
					@if(Auth::user()->user_type == 'user' || Auth::user()->role_id == 17)
					  <th><input type="checkbox" id="selectAll" value="SelectAll"/></th>
					@endif

					  	<th>{{ _lang('Company Name') }}</th>
						<th>{{ _lang('Phone') }}</th>
						<th>{{ _lang('Address') }}</th>

						<th>{{ _lang('Status') }}</th>
						<th>{{ _lang('Sales Person ') }}</th>
					<!--	<th>{{ _lang('Marketing Person') }}</th>-->
						
						<th>{{ _lang('TimeZone') }}</th>
						<th>{{ _lang('State') }}</th>
						<th>{{ _lang('Created Date ') }}</th>
						<th class="text-center">{{ _lang('Action') }}</th>
					</thead>
					<tbody>  
					    
					</tbody>
				</table>
			</div>
		</div>
	</div>
</div>

@endsection

@section('js-script')
<!--<script src="{{ URL::asset('/backend/assets/js/ajax-datatable/leads.js') }}"></script>-->
<script>
    (function($) {

	"use strict";

		var selectedIds = [];

	 var leads_table = $('#leads_table').DataTable({

		processing: true,

		serverSide: true,

		ajax: ({

			url : _url + '/leads/get_table_data',

			method: "POST",

			data: function (d) {
			    

				d._token =  $('meta[name="csrf-token"]').attr('content');

                

                if($('select[name=assigned_user_id]').val() != ''){

	                d.assigned_user_id = $('select[name=assigned_user_id]').val();

	            }
	             
                
                if($('.search-filter').val() != ''){

	                d.keyword = $('.search-filter').val();

	            }
	            
	            if($('.search-status_date').val() != ''){
	                d.status_date = $('.search-status_date').val();

	            }
	            
	            if($('.search-email').val() != ''){

	                d.email = $('.search-email').val();

	            }
                

                if($('select[name=lead_status_id]').val() != null){

                	d.lead_status_id = JSON.stringify($('select[name=lead_status_id]').val());

                }



                if($('select[name=lead_source_id]').val() != ''){

	                d.lead_source_id = $('select[name=lead_source_id]').val();

	            }



                if($('select[name=country]').val() != ''){

	                d.country = $('select[name=country]').val();

	            }
	            if($('select[name=time_zone]').val() != ''){

	                d.time_zone = $('select[name=time_zone]').val();

	            }
	             if($('select[name=zone_state]').val() != ''){

	                d.zone_state = $('select[name=zone_state]').val();

	            }
	            
	            if($('select[name=project_type]').val() != ''){

	                d.project_type = $('select[name=project_type]').val();

	            }

            },

			 error: function (request, status, error) {

				console.log(request.responseText);

			 }

		}),
		"columns" : [
			{
				data : 'id', name : 'id'
			},
				@if(Auth::user()->user_type == 'user' || Auth::user()->role_id == 17)

			{
				targets: 0,
				data: null,
				className: 'text-center',
				searchable: false,
				orderable: false,
				render: function (data, type, full, meta) {
					return '<input type="checkbox" class="select-checkbox" name="check" value="' + data.id + '">';
				},
				width: "5%"
			},
				@endif
		   /* { data : 'id', name : 'id' },*/
		    	{ data : 'company_name', name : 'company_name' },

		/*	{ data : 'name', name : 'name' },

			{ data : 'email', name : 'email' },*/

			{ data : 'phone', name : 'phone' },
			{ data : 'address', name : 'address' },

			{ data : 'lead_status.title', name : 'lead_status.title' },
			
			{ data : 'assigned_user.name', name : 'assigned_user.name' },
			
		/*	{ data : 'marketing_user.name', name : 'marketing_user.name' },*/
			
			/*{ data : 'country', name : 'country' },*/
			{ data : 'zonename.name', name : 'zonename.name' },
			{ data : 'zone_state', name : 'zone_state' },
			{ data : 'created_at', name : 'created_at' },

			{ data : "action", name : "action" },

		],
		responsive: true,

		"bStateSave": true,

		"bAutoWidth":false,	

		"ordering": false,

		"searching": false,

		"language": {

		   "decimal":        "",

		   "emptyTable":     $lang_no_data_found,

		   "info":           $lang_showing + " _START_ " + $lang_to + " _END_ " + $lang_of + " _TOTAL_ " + $lang_entries,

		   "infoEmpty":      $lang_showing_0_to_0_of_0_entries,

		   "infoFiltered":   "(filtered from _MAX_ total entries)",

		   "infoPostFix":    "",

		   "thousands":      ",",

		   "lengthMenu":     $lang_show + " _MENU_ " + $lang_entries,

		   "loadingRecords": $lang_loading,

		   "processing":     $lang_processing,

		   "search":         $lang_search,

		   "zeroRecords":    $lang_no_matching_records_found,

		   "paginate": {

			  "first":      $lang_first,

			  "last":       $lang_last,

			  "next":       $lang_next,

			  "previous":   $lang_previous

		   }

		}

	});

	

	$('.select-filter').on('change', function(e) {

        leads_table.draw();

    });
    
    $(".search-filter").keyup(function(){

        leads_table.draw();

    });
    
    $(".search-email").keyup(function(){

        leads_table.draw();

    });

		/*$('#selectAll').on('click', function (e) {
			e.preventDefault();
			if (this.click) {
				$('.select-checkbox').each(function () {
					$(this).prop("checked", true);
					$(this).toggleClass('selected');
					selectedIds.push(this.value);
				});
				console.log(selectedIds);
			}
		});*/
		$('#selectAll').on('click',function(){

			if(this.checked){
				/*$('.checkbox').each(function(){
					this.checked = true;
					selectedIds.push(this.value);
				});*/
				$('.select-checkbox').each(function () {
					this.checked = true;
					$(this).prop("checked", true);
					$(this).toggleClass('selected');
					selectedIds.push(this.value);
				});
				console.log(selectedIds);
			}else{
				$('.select-checkbox').each(function(){
					this.checked = false;

				});
				selectedIds = [];
			}
		});

		$('.select-checkbox').on('click',function(){
			if($('.select-checkbox:checked').length == $('.select-checkbox').length){
				$('#selectAll').prop('checked',true);
			}else{
				$('#selectAll').prop('checked',false);
			}
		});


})(jQuery);


</script>
<script>
	$(document).ready(function() {
		$("#button").click(function(){
			var arr = [];
			$.each($("input[name='check']:checked"), function(){
				arr.push($(this).val());
			});
			var Assignuserid=$('#select2ID').val();
if(!Assignuserid){
	alert("Please Select Assign User");
	return false;
}
			if(!Assignuserid){
				alert("Please Select Assign User");
				return false;
			}
			var ids =""+ arr.join(", ");
			if(!ids){
				alert("Your selected lead is empty");
				return  false;
			}
			//alert("Your selected languages are: " + arr.join(", "));
			const ids_array = ids.split(',');
			//alert(ids_array)
			$.ajax({
				url: "{{url('leads/assign-leads')}}",
				type: "POST",
				data: {
					assigned_user_id: Assignuserid,
					leasids: ids_array,
					_token: '{{csrf_token()}}'
				},
				dataType: 'json',
				success: function (result) {
window.location.reload();
				}
			});
		});
	});
</script>
<script type="text/javascript">
$(function() {

    var start = moment().subtract(29, 'days');
    var end = moment();

    function cb(start, end) {
        $('input[name="status_date"]').html(start.format('YYYY-MM-DD') + ' - ' + end.format('YYYY-MM-DD'));
    }

    $('input[name="status_date"]').daterangepicker({
        timePicker: false,
        startDate: start,
        endDate: end,
        locale: {
      format: 'YYYY-MM-DD'
    },
        ranges: {
           'Today': [moment(), moment()],
           'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
           'Last 7 Days': [moment().subtract(6, 'days'), moment()],
           'Last 30 Days': [moment().subtract(29, 'days'), moment()],
           'This Month': [moment().startOf('month'), moment().endOf('month')],
           'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
        }
    }, cb);

    cb(start, end);

});
</script>

 <script>
        $(document).ready(function () {
            $('#time_zone').on('change', function () {
                var idCountry = this.value;
                $("#zone_state").html('');
                $.ajax({
                    url: "{{url('fetch-states')}}",
                    type: "POST",
                    data: {
                        zone_id: idCountry,
                        _token: '{{csrf_token()}}'
                    },
                    dataType: 'json',
                    success: function (result) {
                        $('#zone_state').html('<option value="">Select State</option>');
                        $.each(result.states, function (key, value) {
                            $("#zone_state").append('<option value="' + value
                                .name + '">' + value.name + '</option>');
                        });
                    }
                });
            });
            
        });

    </script>

@endsection