@extends('admin.index')
@section('content')
    @php
        use App\Models\CompanyData;
        $DefC=CompanyData::orderBy('id','desc')->first();
        $title=trans('admin.ExceptProfits');
    @endphp
  <title>{{trans('admin.ExceptProfits')}}</title>

    <main id="js-page-content" role="main" class="page-content">
                    <ol class="breadcrumb page-breadcrumb no-print">
                        <li class="breadcrumb-item"><a href="javascript:void(0);"> {{trans('admin.Reports')}} </a></li>
                        <li class="breadcrumb-item active">{{trans('admin.ExceptProfits')}} </li>
                        <li class="position-absolute pos-top pos-right d-none d-sm-block"><span class="js-get-date"></span></li>
                    </ol>
                    <div class="subheader">

                    </div>
                                                        <!-- Head Of Print -->
        @include('admin.layouts.PrintHeader')
                    <div class="row">
                        <div class="col-xl-12">
                            <div id="panel-1" class="panel">
                                <div class="panel-hdr no-print">
                                    <h2>
                                        <span class="fw-300"><i>  {{trans('admin.ExceptProfits')}}</i></span>
                                    </h2>

                                    <div class="panel-toolbar">
                                        <button class="btn btn-sm btn-primary waves-effect waves-themed d-none" onclick="window.print()" style="margin-left:3px"><i class="fal fa-print"></i> {{trans('admin.Print')}}</button>
                                        <button class="btn btn-primary btn-sm mx-3" data-toggle="dropdown">Table Style</button>
                                      @include('admin.layouts.toolbar')
                                    </div>

                                </div>
                                <div class="panel-container show">
                                    <div class="panel-content">
                                                 <div class="row">
                                        <div class="col-md-11 m-1" style="display: none" >
                                            <form action="{{url('ExceptProfitsFilterTwo')}}" method="get" style="display: none">

                                                <div class="form-row">

                                                    <div class="form-group col-lg-4 col-4-print">
                                                        <label class="form-label" for="">  {{trans('admin.Group')}}  </label><span class="strick">*</span>
                                                        <select class="select2 form-control w-100" id="group" name="group">
                                                            <option value="">{{trans('admin.Group')}}</option>
                                                            @foreach($ItemsGroups as $groups)
                                                                <option value="{{$groups->id}}" @if($groups->id == $group) selected @endif>
                                                                    {{app()->getLocale() == 'ar' ?$groups->Name :$groups->NameEn}}
                                                                </option>
                                                            @endforeach
                                                        </select>
                                                    </div>

                                                    <div class="form-group col-lg-4 col-4-print">
                                                        <label class="form-label" for="">  {{trans('admin.Brand')}}  </label>
                                                        <select class="select2 form-control w-100" id="brand" name="brand">
                                                            <option value="">{{trans('admin.Brand')}}</option>
                                                            @foreach($Brands as $brandx)
                                                                <option value="{{$brandx->id}}" @if($brandx->id == $brand) selected @endif>

                                                                    {{app()->getLocale() == 'ar' ?$brandx->Name :$brandx->NameEn}}
                                                                </option>
                                                            @endforeach
                                                        </select>
                                                    </div>



                                                    <div class="form-group col-lg-4 col-4-print">
                                                        <label class="form-label" for="">  {{trans('admin.Stores')}}  </label><span class="strick">*</span>
                                                        <select class="select2 form-control w-100" id="Store" name="Store">
                                                            <option value="">{{trans('admin.Stores')}}</option>
                                                            @foreach($Stores as $stores)
                                                                <option value="{{$stores->id}}" @if($stores->id == $store) selected @endif>

                                                                    {{app()->getLocale() == 'ar' ?$stores->Name :$stores->NameEn}}
                                                                </option>
                                                            @endforeach
                                                        </select>
                                                    </div>


                                                    <div class="form-group col-lg-12 no-print">
                                                        <div class="input-items position-re">
                                                            <input type="text" id="search" class="form-control" value="{{$search}}" name="search" placeholder="{{trans('admin.Search_For_Products')}}">
                                                            @if(app()->getLocale() == 'ar' )
                                                                <i class="fal fa-barcode-alt" style="position:absolute ;top:5px;left:3px;"></i>
                                                            @else
                                                                <i class="fal fa-barcode-alt" style="position:absolute ;top:5px;right: 0;left:auto;"></i>
                                                            @endif
                                                        </div>
                                                    </div>
                                                    <div class="form-group col-lg-1 no-print" style="padding: 22px;">

                                                        <button type="submit" class="btn btn-primary"><i class="fal fa-search"></i></button>

                                                    </div>

                                                </div>
                                            </form>
                                        </div>

                                        </div>

                                        <!-- datatable start -->
                                        <div id="mobile-overflow">
        <table id="X" class="table table-bordered table-hover table-striped w-100 mobile-width">
                                            <thead class="bg-highlight">
                                                <tr>
                                                     <th>{{trans('admin.Code')}} </th>
                                                    <th>{{trans('admin.Name')}} </th>
                                                    <th>{{trans('admin.Unit')}} </th>
                                                    <th>{{trans('admin.Qty')}} </th>
                                                    <th>{{trans('admin.Price')}} </th>
                                                    <th>{{trans('admin.Price_Two')}} </th>
                                                    <th>{{trans('admin.Price_Three')}} </th>
                                                    <th>{{trans('admin.Cost')}} </th>
                                                    <th>{{trans('admin.Total_Cost')}} </th>
                                                    <th>{{trans('admin.Total_Price_Sale1')}} </th>
                                                    <th>{{trans('admin.Total_Price_Sale2')}} </th>
                                                    <th>{{trans('admin.Total_Price_Sale3')}} </th>
                                                    <th>{{trans('admin.Total_Profit')}}  1 ({{trans('admin.Precnet')}}%)</th>
                                                    <th> {{trans('admin.Total_Profit')}} 2 ({{trans('admin.Precnet')}}%)</th>
                                                    <th>{{trans('admin.Total_Profit')}}  3 ({{trans('admin.Precnet')}}%)</th>
                                                </tr>
                                            </thead>
                                            <tbody class="Data"  id="data-wrapper">


                                            </tbody>
                                        </table>
                                        </div>

                                        <div id="mobile-overflow">
        <table  class="table table-bordered table-hover table-striped w-100 mobile-width">
                                            <thead class="bg-highlight">
                                                <tr>
                                                    <th>{{trans('admin.Total_Cost')}} </th>
                                                    <th>{{trans('admin.Total_Profit')}}  1</th>
                                                    <th>({{trans('admin.Precnet')}}%)</th>
                                                    <th>{{trans('admin.Total_Profit')}} 2</th>
                                                    <th>({{trans('admin.Precnet')}}%)</th>
                                                    <th>{{trans('admin.Total_Profit')}} 3</th>
                                                    <th>({{trans('admin.Precnet')}}%)</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                     <tr>
                                    <td id="TC"></td>
                                    <td id="TP1"></td>
                                    <td id="TPP1"></td>
                                    <td id="TP2"></td>
                                    <td id="TPP2"></td>
                                    <td id="TP3"></td>
                                    <td id="TPP3"></td>
                                    </tr>

                                            </tbody>
                                        </table>
                                        </div>


                                        <button style="width: 100%" class="text-center btn btn-primary" id="btn-more"><i class="fal fa-plus">{{trans('admin.More')}}</i></button>

                                        <div class="auto-load text-center">
                                            <svg version="1.1" id="L9" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
                                                 x="0px" y="0px" height="60" viewBox="0 0 100 100" enable-background="new 0 0 0 0" xml:space="preserve">
                <path fill="#000"
                      d="M73,50c0-12.7-10.3-23-23-23S27,37.3,27,50 M30.9,50c0-10.5,8.5-19.1,19.1-19.1S69.1,39.5,69.1,50">
                    <animateTransform attributeName="transform" attributeType="XML" type="rotate" dur="1s"
                                      from="0 50 50" to="360 50 50" repeatCount="indefinite" />
                </path>
            </svg>
                                        </div>


                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
    </main>

                                        <!-- datatable end -->

<input type="hidden" id="COUNT" value="{{$ProdsCount}}">
@endsection

@push('js')
   <link rel="stylesheet" media="screen, print" href="{{asset('Admin/css/datagrid/datatables/datatables.bundle.css')}}">
    <link rel="stylesheet" media="screen, print" href="{{asset('Admin/css/formplugins/select2/select2.bundle.css')}}">

    <script src="{{asset('Admin/js/datagrid/datatables/datatables.export.js')}}"></script>
    <script src="{{asset('Admin/js/datagrid/datatables/datatables.bundle.js')}}"></script>
    <script src="{{asset('Admin/js/formplugins/select2/select2.bundle.js')}}"></script>
    <script>
        $(document).ready(function()
        {
            $(function()
            {
                $('.select2').select2();

                $(".select2-placeholder-multiple").select2(
                {
                    placeholder: "Select State"
                });
                $(".js-hide-search").select2(
                {
                    minimumResultsForSearch: 1 / 0
                });
                $(".js-max-length").select2(
                {
                    maximumSelectionLength: 2,
                    placeholder: "Select maximum 2 items"
                });
                $(".select2-placeholder").select2(
                {
                    placeholder: "Select a state",
                    allowClear: true
                });

                $(".js-select2-icons").select2(
                {
                    minimumResultsForSearch: 1 / 0,
                    templateResult: icon,
                    templateSelection: icon,
                    escapeMarkup: function(elm)
                    {
                        return elm
                    }
                });

                function icon(elm)
                {
                    elm.element;
                    return elm.id ? "<i class='" + $(elm.element).data("icon") + " mr-2'></i>" + elm.text : elm.text
                }

                $(".js-data-example-ajax").select2(
                {
                    ajax:
                    {
                        url: "https://api.github.com/search/repositories",
                        dataType: 'json',
                        delay: 250,
                        data: function(params)
                        {
                            return {
                                q: params.term, // search term
                                page: params.page
                            };
                        },
                        processResults: function(data, params)
                        {
                            // parse the results into the format expected by Select2
                            // since we are using custom formatting functions we do not need to
                            // alter the remote JSON data, except to indicate that infinite
                            // scrolling can be used
                            params.page = params.page || 1;

                            return {
                                results: data.items,
                                pagination:
                                {
                                    more: (params.page * 30) < data.total_count
                                }
                            };
                        },
                        cache: true
                    },
                    placeholder: 'Search for a repository',
                    escapeMarkup: function(markup)
                    {
                        return markup;
                    }, // let our custom formatter work
                    minimumInputLength: 1,
                    templateResult: formatRepo,
                    templateSelection: formatRepoSelection
                });

                function formatRepo(repo)
                {
                    if (repo.loading)
                    {
                        return repo.text;
                    }

                    var markup = "<div class='select2-result-repository clearfix d-flex'>" +
                        "<div class='select2-result-repository__avatar mr-2'><img src='" + repo.owner.avatar_url + "' class='width-2 height-2 mt-1 rounded' /></div>" +
                        "<div class='select2-result-repository__meta'>" +
                        "<div class='select2-result-repository__title fs-lg fw-500'>" + repo.full_name + "</div>";

                    if (repo.description)
                    {
                        markup += "<div class='select2-result-repository__description fs-xs opacity-80 mb-1'>" + repo.description + "</div>";
                    }

                    markup += "<div class='select2-result-repository__statistics d-flex fs-sm'>" +
                        "<div class='select2-result-repository__forks mr-2'><i class='fal fa-lightbulb'></i> " + repo.forks_count + " Forks</div>" +
                        "<div class='select2-result-repository__stargazers mr-2'><i class='fal fa-star'></i> " + repo.stargazers_count + " Stars</div>" +
                        "<div class='select2-result-repository__watchers mr-2'><i class='fal fa-eye'></i> " + repo.watchers_count + " Watchers</div>" +
                        "</div>" +
                        "</div></div>";

                    return markup;
                }

                function formatRepoSelection(repo)
                {
                    return repo.full_name || repo.text;
                }
            });
        });

    </script>
    <script>
        //_fnFeatureHtmlLength();
        $(document).ready(function () {
            // Setup - add a text input to each footer cell
            $('#dt-basic-example thead tr').clone(true).appendTo('#dt-basic-example thead');
            $('#dt-basic-example thead tr:eq(1) th').each(function (i) {
                var title = $(this).text();
                $(this).html('<input type="text" class="form-control form-control-sm" placeholder="Search ' + title + '" />');


                $('input', this).on('keyup change', function () {
                    if (table.column(i).search() !== this.value) {
                        table
                            .column(i)
                            .search(this.value)
                            .draw();
                    }
                });
            });
            var table = $('#dt-basic-example').DataTable(
                {
                    // responsive: true,
                    orderCellsTop: true,
                    fixedHeader: true,
                    lengthChange: true,

                    dom: "<'row mb-3'<'col-sm-12 col-md-3 d-flex align-items-center justify-content-start'f><'col-sm-12 col-md-9 d-flex align-items-center justify-content-end'B>>" +
                        "<'row'<'col-sm-12'tr>>" +
                        "<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",

                    buttons: [
                        {
                            extend: 'pageLength',
                            className: 'btn-outline-default'
                        },
                        {
                            extend: 'colvis',
                            text: 'Column Visibility',
                            titleAttr: 'Col visibility',
                            className: 'btn-outline-default'
                        },
                        {
                            extend: 'pdfHtml5',
                            text: 'PDF',
                            titleAttr: 'Generate PDF',
                            className: 'btn-outline-danger btn-sm mr-1'
                        },
                        {
                            extend: 'excelHtml5',
                            text: 'Excel',
                            titleAttr: 'Generate Excel',
                            className: 'btn-outline-success btn-sm mr-1'
                        },
                        {
                            extend: 'csvHtml5',
                            text: 'CSV',
                            titleAttr: 'Generate CSV',
                            className: 'btn-outline-primary btn-sm mr-1'
                        },
                        {
                            extend: 'copyHtml5',
                            text: 'Copy',
                            titleAttr: 'Copy to clipboard',
                            className: 'btn-outline-primary btn-sm mr-1'
                        },
                        {
                            extend: 'print',
                            text: 'Print',
                            titleAttr: 'Print Table',
                            className: 'btn-outline-primary btn-sm'
                        }
                    ],
                });
            $('.js-thead-colors a').on('click', function () {
                var theadColor = $(this).attr("data-bg");
                console.log(theadColor);
                $('#dt-basic-example thead').removeClassPrefix('bg-').addClass(theadColor);
            });

            $('.js-tbody-colors a').on('click', function () {
                var theadColor = $(this).attr("data-bg");
                console.log(theadColor);
                $('#dt-basic-example').removeClassPrefix('bg-').addClass(theadColor);
            });

        });

    </script>


   <!-- Unit Code and Name V -->
   <script>
       function  UnitCodeStart(x){

           var countryId = $('#UnitStart'+x).val();
           var Pro = $('#Product'+x).val();
           var code = $('#CodeStart'+x).val();
           var Small = $('#SMALLAVG'+x).val();
           var store = $('#Store').val();
           if(countryId) {
               $.ajax({
                   url: 'UnitNameCodeInventoryFilterTWO',
                   type:"GET",
                   data:{
                       id:countryId,
                       Pro:Pro,
                       code:code,
                       store:store,
                       small:Small,
                   },
                   dataType:"json",
                   beforeSend: function(){
                       $('#loader').css("visibility", "visible");
                   },

                   success:function(data) {
                       $.each(data, function(key, value){

                           $('#Qty'+x).val(data.qty);
                           $('#AVG'+x).val(parseFloat(data.price));
                           var AVG=  $('#AVG'+x).val();
                           var Qty=  $('#Qty'+x).val();

                           var Rsu = parseFloat(Qty) * parseFloat(AVG) ;

                           $('#COST'+x).val(parseFloat(Rsu));



                           $.fn.rowCount = function() {
                               return $('tr', $(this).find('tbody')).length;
                           };

                           var rowctr = $('#X').rowCount();

                           var sumQ = 0;
                           $('.Qun').each(function(){
                               sumQ += parseFloat($(this).val());
                           });

                           var sumT = 0;
                           $('.Tot').each(function(){
                               sumT += parseFloat($(this).val());
                           });

                           $('#PRONUMS').text(parseFloat(rowctr));
                           $('#TOTALQTY').text(parseFloat(sumQ));
                           $('#TOTALCOST').text(parseFloat(sumT));

                       });

                   },
                   complete: function(){
                       $('#loader').css("visibility", "hidden");
                   }
               });
           } else {

               $('select[name="state"]').empty();
           }

       }
   </script>

   <!-- Unit Code and Name -->
   <script>
       function  UnitCodeStartt(x){

           var countryId = $('#UnitStart'+x).val();
           var Pro = $('#Product'+x).val();
           var code = $('#CodeStart'+x).val();
           var store = $('#Store').val();
           var Small = $('#SMALLAVG'+x).val();
           if(countryId) {
               $.ajax({
                   url: 'UnitNameCodeInventoryFilterTWO',
                   type:"GET",
                   data:{
                       id:countryId,
                       Pro:Pro,
                       code:code,
                       store:store,
                       small:Small,
                   },
                   dataType:"json",
                   beforeSend: function(){
                       $('#loader').css("visibility", "visible");
                   },

                   success:function(data) {
                       $.each(data, function(key, value){

                           $('#Qty'+x).val(data.qty);
                           $('#CodeStart'+x).val(data.code);
                           $('#AVG'+x).val(parseFloat(data.price));
                           var AVG=  $('#AVG'+x).val();
                           var Qty=  $('#Qty'+x).val();

                           var Rsu = parseFloat(Qty) * parseFloat(AVG) ;

                           $('#COST'+x).val(parseFloat(Rsu));

                           $.fn.rowCount = function() {
                               return $('tr', $(this).find('tbody')).length;
                           };

                           var rowctr = $('#X').rowCount();

                           var sumQ = 0;
                           $('.Qun').each(function(){
                               sumQ += parseFloat($(this).val());
                           });

                           var sumT = 0;
                           $('.Tot').each(function(){
                               sumT += parseFloat($(this).val());
                           });

                           $('#PRONUMS').text(parseFloat(rowctr));
                           $('#TOTALQTY').text(parseFloat(sumQ));
                           $('#TOTALCOST').text(parseFloat(sumT));


                       });

                   },
                   complete: function(){
                       $('#loader').css("visibility", "hidden");
                   }
               });
           } else {

               $('select[name="state"]').empty();
           }

       }
   </script>

<!--  Filter Paginate -->
 <script>


     var group = $('#group').val();
     var brand = $('#brand').val();
     var Store = $('#Store').val();
     var search = $('#search').val();

        var page = 1;
        infinteLoadMore(page);
   $(document).on('click', '#btn-more', function(){
                page++;

                   var Auto =  $('.auto-load').text();
                  if(Auto !=  'No More'){
                infinteLoadMore(page);
                  }else{

         var TotCost = 0;
   $('.TotCost').each(function(){
   TotCost += parseFloat($(this).val());
   });


        var TotP1 = 0;
   $('.TotP1').each(function(){
   TotP1 += parseFloat($(this).val());
   });

                var TotP2 = 0;
   $('.TotP2').each(function(){
   TotP2 += parseFloat($(this).val());
   });


        var TotP3 = 0;
   $('.TotP3').each(function(){
   TotP3 += parseFloat($(this).val());
   });

                  var TotPo = 0;
   $('.TotPo').each(function(){
   TotPo += parseFloat($(this).val());
   });


                  var TotPt = 0;
   $('.TotPt').each(function(){
   TotPt += parseFloat($(this).val());
   });


                  var TotPth = 0;
   $('.TotPth').each(function(){
   TotPth += parseFloat($(this).val());
   });


var R=( ( parseFloat(TotPo) - parseFloat(TotCost) )  / parseFloat(TotCost) ) * 100 ;
var RR=( ( parseFloat(TotPt) - parseFloat(TotCost) )  / parseFloat(TotCost) ) * 100 ;
var RRR=( ( parseFloat(TotPth) - parseFloat(TotCost) )  / parseFloat(TotCost) ) * 100 ;


    $('#TC').text(parseFloat(TotCost).toFixed(2));
    $('#TP1').text(parseFloat(TotP1).toFixed(2));
   $('#TP2').text(parseFloat(TotP2).toFixed(2));
   $('#TP3').text(parseFloat(TotP3).toFixed(2));



     $('#TPP1').text(parseFloat(R).toFixed(2));
   $('#TPP2').text(parseFloat(RR).toFixed(2));
   $('#TPP3').text(parseFloat(RRR).toFixed(2));

      if(parseFloat(R).toFixed(2) == 'Infinity'){
         $('#TPP1').text(parseFloat(0).toFixed(2));
          }

             if(parseFloat(RR).toFixed(2) == 'Infinity'){
            $('#TPP2').text(parseFloat(0).toFixed(2));
          }

             if(parseFloat(RRR).toFixed(2) == 'Infinity'){
           $('#TPP3').text(parseFloat(0).toFixed(2));
          }



                         if ($.fn.DataTable.isDataTable('#X')) {

    $('#X').dataTable().fnDestroy();

}

    var table = $('#X').DataTable(
                {
                    retrieve: true,
                    responsive: true,
                    orderCellsTop: true,
                    fixedHeader: false,
                    lengthChange: false,
                     pageLength : 1000000,
                    dom: 'Bfrtip',

                    buttons: [
                        {
                            extend: 'pageLength',
                            className: 'btn-outline-default'
                        },
                        {
                            extend: 'colvis',
                            text: 'Column Visibility',
                            titleAttr: 'Col visibility',
                            className: 'btn-outline-default'
                        },

                        {
                            extend: 'excelHtml5',
                            exportOptions: {
                                format: {
                                    body: function ( inner, rowidx, colidx, node ) {
                                        if ($(node).children("select").length > 0) {
                                            // we are in a cell containing a "select" drop-down - so, get it:
                                            var selectNode = node.firstElementChild;
                                            var txt = selectNode.options[selectNode.selectedIndex].text;
                                            //var txt = selectNode.options[selectNode.selectedIndex].text;
                                            return txt;
                                        } else {

                                            if ($(node).children("input").length > 0) {
                                                return $(node).children("input").first().val();
                                            } else {
                                                return inner;
                                            }


                                        }
                                    }
                                }
                            },

                            text: 'Excel',
                            titleAttr: 'Generate Excel',
                            className: 'btn-outline-success btn-sm mr-1'
                        },

                        {
                            extend: 'print',
                            text: 'Print',
                            titleAttr: 'Print Table',
                            className: 'btn-outline-primary btn-sm'
                        }
                    ],
                });


                        $('#btn-more').hide();
                  }


        });
        function infinteLoadMore(page) {
            $.ajax({
                    url: "ExceptProfitsFilterTwo?page=" + page,
                    datatype: "html",
                data:{
                       group:group,
                     brand:brand,
                     Store:Store,
                     search:search
                },
                    type: "get",
                    beforeSend: function () {
                        $('.auto-load').show();
                            $('#btn-more').show();
                    },
                     success:function(data)
                    {

                        if(data == ''){

                     $('.auto-load').html("No More");
                        return;

                           }else{
                     $('.auto-load').hide();
                    $("#data-wrapper").append(data);
                           }
                        }

                })

                .fail(function (jqXHR, ajaxOptions, thrownError) {
                    console.log('Server error occured');
                });


        }

    </script>

@endpush
