@extends('layouts.backend')

@section('extraCss')
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/fixedheader/3.1.2/css/fixedHeader.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/fixedcolumns/3.3.3/css/fixedColumns.dataTables.min.css">
<link href="https://cdn.datatables.net/buttons/1.7.0/css/buttons.dataTables.min.css" rel="stylesheet">
<style type="text/css">
table.dataTable {    
  margin-top: 0px !important; 
  margin-bottom: 0px !important;
}

.fieldset{
    padding: 1rem !important;
    border : 2px dashed #d0d7dd !important;  

}

table.dataTable tr.odd { background-color: rgb(240, 241, 243);  }
table.dataTable tr.even{ background-color: white;  }
</style>
@endsection

@php
      
  
    $spscount = \App\CustomerPlan::with('customerRef')->whereHas('customerRef', function ($q) use ($pos_id)
                            {
                               $q->whereIn('warehouse_id', $pos_id); 
                                $q->Distinct('customer_id');
                            })->where('current', 1)->where('status', 1)->whereBetween('start_date', [$startdate, $enddate])->count(); 
 
    $storesType = [ 1 => 'Suti' , 2 => 'Central' , 3 => 'Shopper' ];
    $reqpos = request("pos_id");
        
@endphp

@section('mainContentArea')
<div class="card card-default">
    <div class="card-header">
        <h4>Daily Sales Summary Report  </h4>
        <a href="{{ route('pos-walkin-list') }}" class="btn btn-info float-right btn-sm" style="margin:10px;"><i class="fa fas fa-list"> Walk List</i>  </a>
    </div>     

<!-- <div class="alert alert-default " style="overflow-x:auto;">
  <form action="{{ route('pos-daily-sales-summary-new-report2') }}" id="productreport">
    <h4>Filter  </h4>
    <div style= "padding:15px;">
        <label><input type="checkbox" value="range" name="filterby" checked> Date Range </label>
        <label><input type="checkbox" value="month" name="filterby"> Month </label>                                             
    </div>                

    <table class="table filterPosSo">     
        <tr>
            <td width="15%">Warehouse</td>
            <td width="15%">Group</td>
            <td width="15%">Store</td>
            <td width="10%" id="sdate">Start Date</td>
            <td width="10%" id="edate">End Date</td>                    
            <td colspan="2">ACTION</td>
        </tr>
        <tr>  
            <td>
                <select name="pos_id[]" id="warehouse" class="input-md"  multiple="multiple" >

                @foreach($ALL_WAREHOUSES as $warehouse)
                <option value="{{ $warehouse->id }}" {{ ( !empty(request("pos_id")) && in_array($warehouse->id, request("pos_id")) ? "selected" : "") }}>{{ $warehouse->warehouse_code . ' ('.$warehouse->name.')' }}</option>
                @endforeach
                </select>
            </td>
            <td>
                <select name="storeType[]" id="storeType" class="input-md" multiple="multiple" > 
                                         
                @foreach($ALL_GROUP as $key => $type)
                <option value="{{ $type->id }}" {{ ( !empty(request("storeType")) && in_array($type->id , request("storeType")) ? "selected" : "")  }}
                {{ ( empty(request("storeType")) ? "selected" : "") }}>{{ $type->name }}</option>
                @endforeach
                </select>
            </td>
            <td>
                <select name="pos_id[]" id="posStore" class="input-md" multiple="multiple">
                </select>
            </td>

             <td>
                <select name="pos_id[]" id="Pos" class="input-md"  multiple="multiple">                                
                @foreach($ALL_POS as $warehouse)
                <option value="{{ $warehouse->id }}" {{ ( !empty(request("pos_id")) && in_array($warehouse->id, request("pos_id")) ? "selected" : "") }}>{{ $warehouse->warehouse_code . ' ('.$warehouse->name.')' }}</option>
                @endforeach
                </select>
            </td> -->                      
         <!--    <td>
                <input type="text" name="startdate" id="startdate" readonly class="form-control datepicker" placeholder="Enter Start date" value="<?php echo empty(request('startdate')) ? date("Y-m-d") : request('startdate') ?>" >
                @if ($errors->has('startdate'))
                <span class="text-danger">{{ $errors->first('startdate') }}</span>
                @endif
            </td>                         

            <td>
                <input type="text" name="enddate" id="enddate" readonly class="form-control datepicker" value="<?php echo empty(request('enddate')) ? date("Y-m-d") : request('enddate') ?>" placeholder="Enter End date" >
                @if ($errors->has('enddate'))
                <span class="text-danger">{{ $errors->first('enddate') }}</span>
                @endif
            </td>                        
           
            <td><button class="btn btn-block btn-success" id="submit" ><i class="fa fas fa-search"></i></button></td>
            <td><button class="btn btn-block btn-warning" type="button" onclick="window.location.href='{{ route('pos-daily-sales-summary-new-report2') }}';"><i class="fa fas fa-refresh"></i></button></td>
        </tr>
    </table>
  </form>
</div>   -->

<div class="alert alert-default " >  
      <form action="{{ route('pos-daily-sales-summary-new-report2') }}" id="productreport">
            <fieldset class="fieldset">
            <legend  style="width:auto !important;color:#97b5d3;"> Filter </legend>       
                <div style= "padding:5px;">
                    <label><input type="checkbox" value="range" name="filterby" checked> Date Range </label>
                    <label><input type="checkbox" value="month" name="filterby"> Month </label>                                             
                </div>

                <div class="col-sm-12 "> </div>               
                
                <div class="row">
                    <div class="col-12 col-sm-12 col-md-4 col-lg-4">
                        <label class="d-block"><b> Warehouse </b></label>
                        <select name="pos_id[]" id="warehouse" class="input-md"  multiple="multiple" >

                            @if($user_id !=11)
                                @foreach($ALL_WAREHOUSES as $warehouse)
                                <option value="{{ $warehouse->id }}" {{ ( !empty(request("pos_id")) && in_array($warehouse->id, request("pos_id")) ? "selected" : "") }}>{{ $warehouse->warehouse_code . ' ('.$warehouse->name.')' }}</option>
                                @endforeach
                            @else
                                @foreach($ALL_WAREHOUSES_arham as $warehouse)
                                    <option value="{{ $warehouse->id }}" {{ ( !empty(request("pos_id")) && in_array($warehouse->id, request("pos_id")) ? "selected" : "") }}>{{ $warehouse->warehouse_code . ' ('.$warehouse->name.')' }}</option>
                                @endforeach
                            @endif                       

                        </select>
                    </div>
                    <div class="col-12 col-sm-12 col-md-4 col-lg-4">
                        <label class="d-block"><b> Group </b></label>
                        <select name="storeType[]" id="storeType" class="input-md" multiple="multiple" > 
                            @if($user_id !=11)                      
                                @foreach($ALL_GROUP as $key => $type)
                                <option value="{{ $type->id }}" {{ ( !empty(request("storeType")) && in_array($type->id , request("storeType")) ? "selected" : "")  }}
                                {{ ( empty(request("storeType")) ? "selected" : "") }}>{{ $type->name }}</option>
                                @endforeach
                            @else
                                @foreach($ALL_GROUP_arham as $key => $type)
                                <option value="{{ $type->id }}" {{ ( !empty(request("storeType")) && in_array($type->id , request("storeType")) ? "selected" : "")  }}
                                {{ ( empty(request("storeType")) ? "selected" : "") }}>{{ $type->name }}</option>
                                @endforeach
                            @endif

                            </select>
                    </div>
                    <div class="col-12 col-sm-12 col-md-4 col-lg-4">
                        <label class="d-block"><b> Store </b></label>
                        <select name="pos_id[]" id="posStore" class="input-md" multiple="multiple">
                            </select>
                    </div>
                    

                </div>
                <div class="row mt-3">
                    <div class="col-12 col-sm-12 col-md-4 col-lg-4">
                        <label class="d-block" id="sdate"><b> Start Date </b></label>
                        <input type="text" name="startdate" id="startdate" readonly class="form-control datepicker" placeholder="Enter Start date" value="<?php echo empty(request('startdate')) ? date("Y-m-d") : request('startdate') ?>" >
                            @if ($errors->has('startdate'))
                            <span class="text-danger">{{ $errors->first('startdate') }}</span>
                            @endif
                    </div>
                    <div class="col-12 col-sm-12 col-md-4 col-lg-4">
                        <label class="d-block" id="edate"><b>End Date </b></label>
                        <input type="text" name="enddate" id="enddate" readonly class="form-control datepicker" value="<?php echo empty(request('enddate')) ? date("Y-m-d") : request('enddate') ?>" placeholder="Enter End date" >
                            @if ($errors->has('enddate'))
                            <span class="text-danger">{{ $errors->first('enddate') }}</span>
                            @endif
                    </div>
                    <div class="col-12 col-sm-12 col-md-4 col-lg-4">
                        <label class="d-block"><b> ACTION </b></label>
                        <button class="btn  btn-success  btn-sm d-inline" id="submit" ><i class="fa fas fa-search"> Search </i></button>
                        <button class="btn btn-primary  btn-sm d-inline" type="button" onclick="window.location.href='{{ route('pos-daily-sales-summary-new-report2') }}';"><i class="fa fas fa-refresh"> Reset </i></button>
                    </div>
                </div>
            </fieldset>  
      </form>
</div> 

<div class="d-flex justify-content-center">
  <div class="spinner-border text-primary " role="status" id="loader_div">
      <span class="sr-only">Loading...</span>
  </div>
</div> 
           
<div class="card-body table-responsive" >
@if(!empty($warehouseName))  <h5> Total SPS : <?php echo $spscount; ?> </h5> @endif
<table class="table cell-border " id="salesSumarryTable">
    <thead>
    <tr>
    <th>Date</th>
    @if($filterby != 'month')
    <th>Day</th>
    @endif
    <th> Store Location</th>
    <th>Foot fall</th>
    <th>Repeat</th>
    <th>New</th>

    <th>Total NOB</th>
    <th>QTY</th>
    <th>UPT</th>
    <th>ABV</th>
    <th>ASP</th>
    <th>SPS Target</th> 
    <th> New SPS </th>   
    <th> Old SPS </th>                  
    <th>MTD</th>
    <th>MRP</th>
    <th>SPS Discount</th>
    <th>Clearence Discount</th>
    <th>Other Offer Discount</th>
    <th>Gift Vouchers</th>
    <th>Reward Points</th>
    <th>Used Wallet Amount </th>
    <th>Used Credit Note </th>
    <th>Realized sale</th> 
    <th>ACH%</th>  
    <th>CONV%</th> 
    <th>0 - 1499</th>   
    <th>1500 - 2499</th>  
    <th>2500 - 4998</th>  
    <th>4999 - 5999</th>   
    <th>6000 - 9999</th>  
    <th>10000 & above</th> 
   
    </tr>
    </thead>
@if(!empty($orders))
    <tbody>
    @php    
    $gtotalCash = $gtotalQty = $gtotalbill = $gtotalmrp = $gtotalspss = $gtotalOffer = $gtotalvocher = $gotherOffer = $gclearence =
    $gtotalreward = $gtotal = $gtotalbill0 = $gtotalbill15 = $gtotalbill25 = $gtotalbill5 = $gtotalbill7 = $gtotalbill10 = $gtotalKurti = $gtotalBottom = $gtotalacceess = $gtotaljewelery = 
    $gtotalother  = $gtotalset = $gtotalDress =  $gtotaldplain = $gtotaldprint = $gtotalJacket = $gtotalsemi = $gtotalsas = $gtotalunsemi = $gtotaljum = $gtotalhomF =
    $gtotalkaf = $gtotalmask = $gtotalsostf = $gtotallongw = $gtotalsnsc = $gtotaltato = $gtotaluni = $gtotalwhu = $averaguabv = $gtotalSPSNew = $gtotalSPSOld = $averagasp = $averagupt = $gtotalSPS = $abv = $asp = 0.00; 
    $gtotalnewcustomer =$gtotaloldcustomer = $gfinal = $gmrp = $gqty = $gtotalfoot = $gwalletdis =$gtotalCnote =$CreditTotal= 0;
    $totalCount = count($orders);

    @endphp
    @foreach($orders as $key => $order)  
    @php 

    $totalTotal = $otherOffer = $clearence = 0; 
    $totalexchangeqty = $order['exchangeqty'];
    $exchangeamount = $order['exchangeamount'];    
 

    //CREDIT NOTE 
    $totalCnote = $order['totalCn']; 
    $gtotalCnote += $order['totalCn']; 

    $order['totalQty'] = $order['totalQty'];    
    $order['totalfinalamt'] = $order['totalfinalamt'] - $totalCnote ;  
    $order['totalMrp'] = $order['totalMrp'];

    
    $gfinal += $order['totalfinalamt'];
    $gmrp += $order['totalMrp'];
    $gqty += $order['totalQty'];

    $totalTotal += $order['totalfinalamt'];

    $gwalletdis += $order['walletAmt'];
    $gtotalfoot += $order['setfootfall']; 
    $gtotalnewcustomer += $order['newcustomer']; 
    $gtotaloldcustomer += $order['oldcustomer']; 

    $gtotalSPS += $order['spscount'];  
    $gtotalSPSOld += $order['oldspscount'];                     

    $gtotalbill += $order['totalBill'];                     

    $dismrp = ($order['totalMrp'] * 10/100);

    $otherOffer = $order['otherOffer'];

    $gotherOffer += $otherOffer;

    $clearence = $order['clearence'];
    $gclearence += $clearence;  

    if($order['totalBill'] > 0)
    {
      $abv= $totalTotal/  $order['totalBill']; 
    }

    if($order['totalQty'] > 0)
    {
      $asp = $totalTotal/  $order['totalQty']; 
    }

    $gtotalspss += $order['totalSpsDiscount'];
    $gtotalvocher += $order['voucher'];  
    $gtotalreward += $order['totalreward'];

    $gtotalbill5 += $order['bill5']; 
    $gtotalbill7 += $order['bill7']; 
    $gtotalbill10 += $order['bill10']; 

    $gtotalbill0 += $order['bill0']; 
    $gtotalbill15 += $order['bill15']; 
    $gtotalbill25 += $order['bill25']; 

    $gtotalKurti += $order['Kurti']; 
    $gtotalBottom += $order['Bottom']; 
    $gtotalacceess += $order['Accessories']; 
    $gtotaljewelery += $order['JEWELLERY']; 
    $gtotalother += $order['All Other']; 
    $gtotalset += $order['KURTA SET']; 
    $gtotalDress += $order['Dresses']; 
  
    $gtotalJacket += $order['Jacket']; 
  
    $gtotalhomF += $order['Home Linen']; 
    $gtotalkaf += $order['KAFTAN']; 
    $gtotalmask += $order['MASK']; 
  
    $gtotallongw += $order['LoungeWear'];
    
    $gtotaltato += $order['TOP N TUNIC'];
    $gtotaluni += $order['Uniform-1'];
   

    @endphp         
    <tr>
        <td >{{$order['date']}}</td>
        @if($filterby != 'month') <td >{{date('l', strtotime($order['date']))}}</td> @endif
        <td >{{$order['store']}}</td>                                
        <td >{{$order['setfootfall']}}</td>
        <td >{{$order['oldcustomer']}}</td>
        <td >{{$order['newcustomer']}}</td>                                
        <td >{{$order['totalBill']}}</td>
        <td >{{$order['totalQty'] }}</td>                                
        <td >{{number_format($order['upt'],2)}}</td>
        <td>{{ number_format((float)$abv, 2, '.', '')  }}</td>
        <td>{{ number_format((float)$asp, 2, '.', '')  }}</td> 

        <td >{{$order['spsTarget']}}</td>  
        <td >{{$order['spscount']}}</td>
        <td >{{$order['oldspscount']}}</td>
        <td >{{$order['mtd']}}</td>
        <td >{{$order['totalMrp'] }}</td>
        <td >{{$order['totalSpsDiscount']}}</td> 
        <td >{{$clearence}}</td> 
        <td>{{$otherOffer}}</td>
        <td>{{$order['voucher']}}</td>
        <td>{{ number_format((float)$order['totalreward'], 2, '.', '')}}</td>
        <td> {{$order['walletAmt']}}</td>
        <td >{{$totalCnote }}</td> 
        <td >{{$totalTotal }}</td> 
        <td >0</td> 
        <td >0</td> 
        <td >{{$order['bill0']}}</td> 
        <td >{{$order['bill15']}}</td> 
        <td >{{$order['bill25']}}</td> 
        <td >{{$order['bill5']}}</td> 
        <td >{{$order['bill7']}}</td> 
        <td >{{$order['bill10']}}</td> 
       
      
    </tr>
    @endforeach
    </tbody> 
    <tfoot>
    <tr>
        <td></td>
        @if($filterby != 'month')  <td></td> @endif
        <td></td>
        <td>{{$gtotalfoot}}</td>
        <td>{{$gtotaloldcustomer}}</td>
        <td>{{$gtotalnewcustomer}}</td>
        <td> {{$gtotalbill}}</td>
      
        <td> {{$gqty}} </td>

        @php   $aupt=$gqty / $gtotalbill; 
        $aabv=$gfinal / $gtotalbill ; 
        $aasp=$gfinal / $gqty; 

        @endphp

        <td>{{number_format($aupt,2)}}</td>
        <td>{{ round ($aabv) }}</td>
        <td>{{ round ($aasp) }}</td>
        <td></td>
        <td> {{round($gtotalSPS)}}</td>
        <td> {{round($gtotalSPSOld)}}</td>                                
        <td></td>
        <td> {{round($gmrp)}} </td>
        <td> {{round($gtotalspss)}} </td>
        <td> {{round($gclearence)}} </td>
        <td> {{round($gotherOffer)}}</td>
        <td> {{round($gtotalvocher)}} </td>
        <td> {{round($gtotalreward)}} </td>
        <td> {{round($gwalletdis)}}</td>
        <td> {{round($gtotalCnote)}}</td> 
        <td> {{round($gfinal)}} </td>
        <td>0</td>
        <td>0</td>
        <td> {{round($gtotalbill0) }} </td>
        <td> {{round($gtotalbill15) }} </td>
        <td> {{round($gtotalbill25) }} </td>
        <td> {{round($gtotalbill5) }} </td>
        <td> {{round($gtotalbill7) }} </td>
        <td> {{round($gtotalbill10) }} </td>
       
       

    </tr>  
    <tr>
        <th>Date</th>
        @if($filterby != 'month')
        <th>Day</th>
        @endif
        <th> Store Location</th>
        <th>Foot fall</th>
        <th>Repeat</th>
        <th>New</th>

        <th>Total NOB</th>
        <th>QTY</th>
        <th>UPT</th>
        <th>ABV</th>
        <th>ASP</th>
        <th>Sps Target</th>  
        <th> New SPS </th>   
        <th> Old SPS </th>   
        <th>MTD</th>                  
        <th>MRP</th>
        <th>SPS Discount</th>
        <th>Clearence Discount</th>
        <th>Other Offer Discount</th>
        <th>Gift Vouchers</th>
        <th>Reward Points</th>
        <th>Used Wallet Amount</th>
        <th>Used Credit Note </th>
        <th>Realized sale</th> 
        <th>ACH%</th>  
        <th>CONV%</th> 
        <th>0 - 1499</th>   
        <th>1500 - 2499</th>  
        <th>2500 - 4998</th>  
        <th>4999 - 5999</th>   
        <th>6000 - 9999</th>  
        <th>10000 & above</th> 
        
    </tr>                 
    </tfoot>

@endif
</table>

</div>
  
</div>
@endsection

@section('extraJs')
<script src="https://cdn.datatables.net/fixedheader/3.1.2/js/dataTables.fixedHeader.min.js" type="text/javascript"></script>
<script src="https://cdn.datatables.net/fixedcolumns/3.3.3/js/dataTables.fixedColumns.min.js" type="text/javascript"></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">

// $(document).ready(function() {

//   $('#salesSumarryTable').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 ,
//     scrollX: true,
//     scrollY: "800px",
//     scrollCollapse: true,
    
//     fixedColumns:   {
//     leftColumns: 3,

//     } 
//   } );

// } );

$(document).ready(function() {   

$('#salesSumarryTable').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 ,
    scrollX: true,
    scrollY: "800px",
    scrollCollapse: true,
    
    fixedColumns:   {
    leftColumns: 3,

    }
  
} );
});

jQuery("#loader_div").hide();
$("#submit").click(function () {

  if (($('#warehouse').val() == '') && ($('#posStore').val() == '')) {
    alert("Please Select Warehouse / Store");
    $("#productreport").attr("disabled", "disabled");
    return false;
  }

  var startDate = document.getElementById("startdate").value;
  var endDate = document.getElementById("enddate").value;

  if ((Date.parse(startDate) > Date.parse(endDate))) {
    alert("End date should be greater than Start date");
    $("#productreport").attr("disabled", "disabled");
    return false;
  }else{
    jQuery("#loader_div").show();
  }

});

$("input[type='checkbox']").on('click', function() {
  $("input[type='checkbox']").not(this).prop('checked', false);
});

var type = $('#storeType').val();
callstores(type);

$("#storeType").on('change', function () { 

var type = $('#storeType').val();
callstores(type);

});

function callstores(type)
{
  var _token   = $('meta[name="csrf-token"]').attr('content');   

  $.ajax({
  url:"{{ route('type-store-list') }}",
  method:"get",
  data:{type: type, _token:_token},
  success:function(res)
  { 

  if(res){ console.log(res);
  $("#posStore").empty();

  $.each(res,function(key,value){ //console.log(key,value);
  $("#posStore").append('<option value="'+key+'" >'+value+'</option>');
  });

  console.log( <?php echo json_encode($reqpos); ?>);
  var values = <?php echo json_encode($reqpos); ?>;
  $.each(values, function(i,e){ console.log(i,e);
      $("#posStore option[value='" + e + "']").prop("selected", true);
  });

  $('#posStore').multiselect({            
  enableFiltering: true,
  allSelectedText: 'All',
  maxHeight: 200,
  includeSelectAllOption: true,
  enableCaseInsensitiveFiltering: true  
  });        

  $('#posStore').multiselect('rebuild');

  }else{
  $("#posStore").empty();
  }
  }

  })
}

</script>
@endsection
