@extends('layouts.backend')
@section('extraCss')
<link href="https://cdn.datatables.net/buttons/1.7.0/css/buttons.dataTables.min.css" rel="stylesheet">
<style type="text/css">
span.multiselect-native-select {
    position: relative;
    display: block;
}
.btn-group, .btn-group-vertical {
    display: block;
}
.custom-select, .dropdown-item {
    width: 100% !important;
}
</style>
@endsection
@section('mainContentArea')
    <div class="card card-default">
        <div class="card-header">
            <h4>Location Manager</h4>
             <button class="btn btn-success float-right btn-sm" type="button"  data-toggle="modal" data-target="#locationModel" id="add-location" style="float:right; margin:10px;">
              <i class="fa fas fa-plus"></i> Add Location</button>
        </div>
        <div class="alert alert-default" >
            <form action="{{ route('locationList') }}" method="get">
               
                <h4>Filter  </h4>
                <table class="table filterPosSo"> 
                    <tr>
                        <td >Group</td>
                        <td >Stuts</td>
                        <td colspan="2">ACTION</td>
                    </tr>
                    <tr>
                        <td width="30%">
                            <select name="location[]"  class="input-md"  multiple="multiple" >                                
                                @foreach($grouplist as $cname)
                                <option value="{{ $cname->id }}" {{ ( !empty(request("location")) && in_array($cname->id, request("location")) ? "selected" : "") }}>{{ $cname->name }}</option>
                                @endforeach
                            </select> 
                        </td>
                        <td>
                            <select name="status" id="status" class="form-control" required>
                                <option value="">select</option>                               
                                <option value="1" {{  (request("status") == '1') ? "selected" : "" }}>Active</option>
                                <option value="0" {{  (request("status") == '0') ? "selected" : "" }}>Inactive</option>
                              
                            </select>
                        </td>
                        
                        <td><button class="btn btn-block btn-success"><i class="fa fas fa-search" id="submit"></i></button></td>
                        <td><button class="btn btn-block btn-warning" type="button" onclick="window.location.href='{{ route('locationList') }}';"><i class="fa fas fa-refresh"></i></button></td>
                   
                    </tr>
                </table>
            </form>
        </div>
        <div class="card-body">         
        <input type="button" style="font-size: 20px;float: right;margin-right: 20px;" class="btn btn-xs btn-info btn-sm" id="active" name="active" value="Active" />  
        <input type="button" style="font-size: 20px;float: right;margin-right: 20px;" class="btn btn-xs btn-danger btn-sm" id="deactive" name="deActive" value="InActive" /> 
        <br><br> <br><br>   
            <table class="table table-striped table-bordered" id="locationTables">
                <thead>
                    <tr>
                        <th>S.No.</th>
                        <th>Name</th>
                        <th>Type</th>
                        <th>Code</th>
                        <th>City</th>
                        <th>Lower Discount</th>
                        <th>Upper Discount</th>
                        <th><input type='checkbox' id='CheckAll'></th> 
                        <th width="100px">Action</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach ($locationlist as $key => $group)
                        @php $color = '' ; 
                              if($group->is_active == 1)
                              {
                                 $color = 'green';
                              }else
                              {
                                 $color = 'red';
                              }                                
                                
                        @endphp
                        
                        <tr style="color:{{$color}}">
                            <td>{{$key + $locationlist->firstItem() }}</td> 
                            <td>{{ empty($group->name) ? 'N/A' : $group->name }}</td>
                            <td>{{ empty($group->stype) ? 'N/A' : $group->stype }}</td>
                            <td>{{ empty($group->warehouse_code) ? 'N/A' : $group->warehouse_code }}</td>
                            <td>{{ empty($group->city) ? 'N/A' : $group->city }}</td>
                            <td>{{ empty($group->lower_disc) ? 'N/A' : $group->lower_disc }}</td>
                            <td>{{ empty($group->upper_disc) ? 'N/A' : $group->upper_disc }}</td>
                            <td><input type='checkbox' name="posID[]" class='checkboxes' value="{{ $group->id }}"></td>
                            <td><a data-id="{{ $group->id }}" id="edit-post" class="btn btn-xs btn-info btn-sm"><i class="fa fas fa-pencil"></i> </a>
                            </td>

                           
                           
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
        @php if($locationlist->count() > 0) { @endphp {!! $locationlist->appends(request()->input())->links() !!} @php } @endphp
    </div>

<!-- Modal -->
<div class="modal fade" id="locationModel" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <!-- Modal Header -->
            <div class="modal-header" >
              <h5> Add Location</h5>
              <button type="button" class="close" data-dismiss="modal">&times;</button> 
               
            </div>
            
            <!-- Modal Body -->
            <div class="modal-body">
                <p class="statusMsg"></p>
                <form role="form">
                    <input id="locationid" type="hidden">
                    <div class="form-group"><label for="hsnname">Name</label><input class="form-control" name="name" id="locname" required value="" placeholder="Enter Name"/></div>
                    <div class="form-group stypes"><label for="hsntype">Type</label><select class="form-control" name="stype" id="loctype" required><option value="">Select Option</option><option value="1">Warehouse</option><option value="2">POS</option></select></div>
                    <div class="form-group store_type"><label for="store_type"> Group Type</label> <button class="btn btn-success float-right btn-sm" type="button"  data-toggle="modal" data-target="#groupModel" id="add-group" style="float:right; margin:10px;">
                    <i class="fa fas fa-plus"></i> Add Group</button><select class="form-control" name="store_type" id="store_type" required><option value="">Select Option</option>@foreach($grouplist as $glist) <option value="{{$glist->id}}">{{$glist->name}}</option> @endforeach </select></div>
                    <div class="form-group" id="fre_type"><label for="hsnFtype">Is Franchisee</label><select class="form-control" name="is_active" id="franchtype" required><option value="">Select Option</option><option value="1">No</option><option value="2">Yes</option></select></div>
                    <div class="form-group"><label for="hsnCcode">Company Code</label><input class="form-control" name="company_code" id="loccode" required value="" placeholder="Enter Company Code"/></div>
                    <div class="form-group"><label for="hsncode">Location Code</label><input class="form-control" name="warehouse_code" id="warecode" required value="" placeholder="Enter  Code"/></div>
                    <div class="form-group"><label for="wphone">Phone</label><input class="form-control" name="phone" id="wphone" required value="" placeholder="Enter  Phone"/></div>
                    <div class="form-group"><label for="wemail">Email</label><input class="form-control" name="email" id="wemail" required value="" placeholder="Enter  Email" type="email"/></div>
                    <div class="form-group"><label for="waddress">Address</label><input class="form-control" name="address" id="waddress" required value="" placeholder="Enter  Address"/></div>
                    <div class="form-group"><label for="wcity">City</label><input class="form-control" name="city" id="wcity" required value="" placeholder="Enter  City"/></div>
                    <div class="form-group"><label for="wstate">State</label><input class="form-control" name="state" id="wstate" required value="" placeholder="Enter  State"/></div>
                    <div class="form-group"><label for="wcontactp">Contact Person</label><input class="form-control" name="contact_person" id="wcontactp" required value="" placeholder="Enter  Contact Person"/></div>
                    <div class="form-group" id="gst_type"><label for="wgstin">GSTIN</label><input class="form-control" name="gstin" id="wgstin" required value="" placeholder="Enter  GSTIN"/></div>
                    <div class="form-group" id="gst_date"><label for="wgstin">GST Date</label><input class="form-control datepicker" name="gst_date" id="wgstdate" required value="" placeholder="Enter  GST Date"/><sub class="text-danger">Date format: YYYY-mm-dd</sub></div>
                    <div class="form-group " id="wdis_type"><label for="wdiscount">Discount</label><input class="form-control" name="discount" id="wdiscount" required value="0" placeholder="Enter  GST Discount" type="number" min="0" step="any"/></div>
                    <div class="form-group" id="wl_type"><label for="lower_disc">Lower Discount (below 1000)</label><input class="form-control" name="lower_disc" id="lower_disc" required value="" placeholder="Enter  GST Discount" type="number" min="0" step="any"/></div>
                    <div class="form-group" id="wu_type"><label for="upper_disc">Upper Discount (above 1000)</label><input class="form-control" name="upper_disc" id="upper_disc" required value="" placeholder="Enter  GST Discount" type="number" min="0" step="any"/></div>
                  
                </form>
            </div>
            
            <!-- Modal Footer -->
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary submitBtn" id="btn-save" onclick="submitLocationForm()">SUBMIT</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="groupModel" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <!-- Modal Header -->
            <div class="modal-header" >
              <h5> Add Group</h5>
              <button type="button" class="close" data-dismiss="modal">&times;</button> 
               
            </div>
            
            <!-- Modal Body -->
            <div class="modal-body">
                <p class="statusMsg"></p>
                <form role="form">
                    
                    <div class="form-group">
                        <label for="inputName">Name</label>                        
                        <input type="text" class="form-control" id="inputName" placeholder="Enter your name" required />
                    </div> 
                    
                    <div class="form-group">
                        <label for="inputMessage">Description</label>                        
                        <textarea class="form-control" id="inputDes" placeholder="Enter your description" required></textarea>
                    </div>
                    <div class="form-group">
                        <label for="inputMessage">Status</label>
                        <select name="status" id="inputstatus" class="form-control" required>
                                <option value="">select</option>                               
                                <option value="1" {{ ( (!empty(request("status")) && (request("status") === 1)) ? "selected" : "") }}>Active</option>
                                <option value="0" {{ ( (!empty(request("status")) && (request("status") === 0)) ? "selected" : "") }}>Deactive</option>
                              
                        </select>                       
                    </div>
                </form>
            </div>
            
            <!-- Modal Footer -->
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary submitBtn" id="btn-save" onclick="submitGroupForm()">SUBMIT</button>
            </div>
        </div>
    </div>
</div>
   
@endsection

@section('extraJs')
<script type="text/javascript" src=" https://www.gyrocode.com/articles/jquery-datatables-column-reordering-and-resizing"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js" ></script>
<script src="https://cdn.datatables.net/buttons/1.7.0/js/buttons.html5.min.js" ></script>

<script type="text/javascript">
i = 0;
$('#active').click(function () {      
    var arr = [];
    $('.checkboxes:checked').each(function () {
            arr[i++] = $(this).val();            
            setLocation($(this).val(),1);
    });
    console.log(arr);
}); 

$('#deactive').click(function () {      
    var arr = [];
    $('.checkboxes:checked').each(function () {
            arr[i++] = $(this).val();            
            setLocation($(this).val(),0);
    });
    console.log(arr);
}); 

function setLocation(pos,status){
    
    var _token   = $('meta[name="csrf-token"]').attr('content'); 
    $.ajax({
        type: "get",
        url: "{{ route('location-status-update') }}",
        data: {
        pos: pos,            
        status:status,              
        _token: _token
        },
        dataType: "json",                       
        success: function(response) { 
            var reason = JSON.stringify(response);  
            var parsed = JSON.parse(reason);            
            console.log(parsed);
            if (parsed.status == false) {
            toastr.error(parsed.info);
            $('.submitBtn').removeAttr("disabled");
            } else {
            toastr.success(parsed.info);
            
            window.location.reload('true');               
            
            }
        }
    });
   
}

$('body').on('click', '#add-location', function () {       
        $('#locname').val('');       
        $('#loctype').val('');
        $('#store_type').val('');
        $('#franchtype').val('');
        $('#loccode').val('');
        $('#warecode').val('');
        $('#wphone').val('');
        $('#wemail').val('');
        $('#waddress').val('');
        $('#wcity').val('');
        $('#wstate').val('');
        $('#wcontactp').val('');
        $('#wgstin').val('');
        $('#wgstdate').val('');
        $('#wdiscount').val('');
        $('#lower_disc').val('');
        $('#upper_disc').val('');
        $('#locationModel .modal-dialog .modal-content .modal-header h5').html("Add Location");
        $('#locationModel .modal-dialog .modal-content .modal-footer #btn-save').html("Submit");
});

$('#loctype').on('change', function() {
 
    if(this.value === '1')
    {
      $('#wdis_type').hide();
      $('#fre_type').hide();
      $('#wl_type').hide();
      $('#wu_type').hide();
      $('#gst_type').hide();
      $('#gst_date').hide();
    }else
    {
      $('#wdis_type').show();
      $('#fre_type').show();
      $('#wl_type').show();
      $('#wu_type').show();
      $('#gst_type').show();
      $('#gst_date').show();
    }
});


function submitLocationForm(){
    
    var locname = $('#locname').val();    
    var loctype = $('#loctype').val();
    var store_type = $('#store_type').val();  
    var franchtype = $('#franchtype').val();    
    var loccode = $('#loccode').val();
    var warecode = $('#warecode').val(); 
    var wphone = $('#wphone').val();    
    var wemail = $('#wemail').val();
    var waddress = $('#waddress').val(); 
    var wcity = $('#wcity').val();    
    var wstate = $('#wstate').val();    
    var wcontactp =  $('#wcontactp').val();
    var wgstin =  $('#wgstin').val();
    var gst_date =  $('#wgstdate').val();
    var wdiscount =  $('#wdiscount').val();
    var lower_disc =  $('#lower_disc').val();
    var upper_disc =  $('#upper_disc').val();
    var locationid =  $('#locationid').val();

    if(loctype === '2')
    {
        if(wgstin.trim() == '' ){
            alert('Please enter GST Number.');
            $('#wgstin').focus();
            return false;
        }else if(gst_date.trim() == '' ){
            alert('Please GST Date.');
            $('#wgstdate').focus();
            return false;
        }else if(wdiscount.trim() == '' ){
            alert('Please enter Discount.');
            $('#wdiscount').focus();
            return false;
       }else if(lower_disc.trim() == '' ){
            alert('Please enter Lower Discount.');
            $('#lower_disc').focus();
            return false;
      }else if(upper_disc.trim() == '' ){
            alert('Please enter Upper Discount.');
            $('#upper_disc').focus();
            return false;
      }
    } 
    
    if(locname.trim() == '' ){
        alert('Please enter name.');
        $('#locname').focus();
        return false;
    }else if(loctype.trim() == '' ){
        alert('Please select Type.');
        $('#loctype').focus();
        return false;
    }else if(store_type.trim() == '' ){
        alert('Please select group Type.');
        $('#store_type').focus();
        return false;
    }if(loccode.trim() == '' ){
        alert('Please enter Company code.');
        $('#loccode').focus();
        return false;
    }if(warecode.trim() == '' ){
        alert('Please enter Location code.');
        $('#warecode').focus();
        return false;
    }if(wphone.trim() == '' ){
        alert('Please enter phone number.');
        $('#wphone').focus();
        return false;
    }if(wemail.trim() == '' ){
        alert('Please enter email id.');
        $('#wemail').focus();
        return false;
    }if(waddress.trim() == '' ){
        alert('Please enter Address.');
        $('#waddress').focus();
        return false;
    }if(wstate.trim() == '' ){
        alert('Please enter State.');
        $('#wstate').focus();
        return false;
    }if(wcity.trim() == '' ){
        alert('Please enter City.');
        $('#wcity').focus();
        return false;
    }if(wcontactp.trim() == '' ){
        alert('Please enter Contact Person Name.');
        $('#wcontactp').focus();
        return false;
    }else{
        var _token   = $('meta[name="csrf-token"]').attr('content'); 
        $.ajax({
            type: "get",
            url: "{{ route('locationsave') }}",
            data: {
            locname: locname,            
            loctype:loctype,
            store_type:store_type,   
            franchtype: franchtype,  
            loccode: loccode,            
            warecode:warecode,
            wphone:wphone,   
            wemail: wemail,
            waddress: waddress,            
            wcity:wcity,
            wstate:wstate,   
            wcontactp: wcontactp,  
            wgstin: wgstin,
            gst_date: gst_date,            
            wdiscount:wdiscount,
            lower_disc:lower_disc,   
            upper_disc: upper_disc, 
            locationid : locationid,   
            _token: _token
            },
            dataType: "json",
            beforeSend: function () {
                $('.submitBtn').attr("disabled","disabled");
               
            },           
            success: function(response) { 
                var reason = JSON.stringify(response);  
                var parsed = JSON.parse(reason);            
                console.log(parsed);
                if (parsed.status == false) {
                toastr.error(parsed.info);
                $('.submitBtn').removeAttr("disabled");
                } else {
                toastr.success(parsed.info);
                
                window.location.reload('true');               
                
                }
            }
        });
    }
}

function submitGroupForm(){
    
    var name = $('#inputName').val();    
    var desc = $('#inputDes').val();
    var status = $('#inputstatus').val();  
    var groupid =  $('#groupid').val();
    if(name.trim() == '' ){
        alert('Please enter name.');
        $('#inputName').focus();
        return false;
    }else if(desc.trim() == '' ){
        alert('Please enter description.');
        $('#inputDes').focus();
        return false;
    }else if(status.trim() == '' ){
        alert('Please select status.');
        $('#inputstatus').focus();
        return false;
    }else{
        var _token   = $('meta[name="csrf-token"]').attr('content'); 
        $.ajax({
            type: "get",
            url: "{{ route('groupsave') }}",
            data: {
            name: name,            
            desc:desc,
            status:status,   
            groupid: groupid,        
            _token: _token
            },
            dataType: "json",
            beforeSend: function () {
               // $('.submitBtn').attr("disabled","disabled");
               
            },           
            success: function(response) { 
                var reason = JSON.stringify(response);  
                var parsed = JSON.parse(reason);            
                console.log(parsed);
                if (parsed.status == false) {
                toastr.error(parsed.info);
                //$('.submitBtn').removeAttr("disabled");
                } else {
                toastr.success(parsed.info);
                $('#store_type').html('');
                $('#groupModel').hide();
                $('#inputName').val('');    
                $('#inputDes').val('');
                $('#inputstatus').val(''); 
                $.each(parsed.data, function(key, value) {  console.log(key, value); 
                $('#store_type').append($("<option></option>").attr("value", value.id).text(value.name)); 
             });
                //window.location.reload('true');               
                
                }
            }
        });
    }
}

$('body').on('click', '#edit-post', function () {
      var post_id = $(this).data('id');
      var _token   = $('meta[name="csrf-token"]').attr('content'); 
        $.ajax({
            type: "get",
            url: "{{ route('locationedit') }}",
            data: {
            id:  post_id,        
            _token: _token
            },
            dataType: "json",                       
            success: function(data) { 
                  $('#locationModel .modal-dialog .modal-content .modal-header h5').html("Edit Location");
                  $('#locationModel .modal-dialog .modal-content .modal-footer #btn-save').html("update");
                  $('#locationModel').modal('show');                  
                    
                    $('#locname').val(data.name); 
                    $('#loccode').val(data.company_code);
                    $('#warecode').val(data.warehouse_code);
                    $('#wphone').val(data.phone);
                    $('#wemail').val(data.email);
                    $('#waddress').val(data.address);
                    $('#wcity').val(data.city);
                    $('#wstate').val(data.state);
                    $('#wcontactp').val(data.contact_person);
                    $('#wgstin').val(data.gstin);
                    $('#wgstdate').val(data.gst_date);
                    $('#wdiscount').val(data.discount);
                    $('#lower_disc').val(data.lower_disc);
                    $('#upper_disc').val(data.upper_disc);
                    $('#locationid').val(data.id);
                    $("#loctype option[value=" + data.stype + "]").attr('selected', true);
                    $("#franchtype option[value=" + data.is_active + "]").attr('selected', true);
                    $("#store_type option[value=" + data.store_type + "]").attr('selected', true);                
            }
        });
      
});

$(document).ready(function() {
$('#locationTables').DataTable( {
  "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],         
  dom: 'Bfrtip',
  buttons: [ 
  'colvis',
  {
  extend: 'excelHtml5',
  autoFilter: true,
  sheetName: 'Exported data',
  exportOptions: {
  columns: ':visible'
  },
  footer: true
  }                     
  ],                   
  colReorder: true,  
  paging: false 
} );

} );
</script>
@endsection
