@extends('layouts.app')
@section('title','Products')
@section('pages')
<style type="text/css">
    .dataTables_filter{
        margin-bottom: 6px;
    }
    .text-left {
        text-align: left !important;
    }
</style>
<link rel="stylesheet/less" type="text/css" href="{{ asset('admin/plugins/datepicker/less/datepicker.less') }}">
<link href="{{ asset('admin/plugins/datepicker/css/datepicker.css')}}" rel="stylesheet" />
<!--breadcrumb-->
<div class="page-breadcrumb d-flex align-items-center mb-3 px-3 px-md-0">
    <div class="breadcrumb-title pe-3"><i class="bi bi-list"></i> Products</div>
    <div class="ps-3">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb mb-0 p-0">
                <li class="breadcrumb-item active" aria-current="page"> Product Details</li>
            </ol>
        </nav>
    </div>
    <div class="ms-auto">
        @if(auth()->user()->can('product-edit'))
        <div class="btn-group">
            <a href="{{route('products.edit',$product->id)}}" class="btn btn-warning" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Edit">
                <i class="bi bi-pencil-square text-white"></i>
            </a>
        </div>
        @endif
        <div class="btn-group">
            <a href="{!! route('products.index') !!}" class="btn btn-info"><i class="bx bx-arrow-back ms-0 me-1"></i>Back</a>
        </div>
    </div>
</div>
<!--end breadcrumb-->

<div class="row auto">
    <div class="col-xl-12 mx-auto">
        <div class="shadow-none radius-5 min-height">
            <div class="row">
                @if(isset($product->description) && $product->description != '')
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-body g-3 row">
                            <div class="table-responsive">
                                <h5 class="mb-0">Item Name: <b>{{$product->name}}</b></h5>
                                <hr class="mb-2">
                                <p>{{$product->description}}</p>
                            </div>
                        </div>
                    </div>
                </div>
                @endif
                <div class="col-md-4">
                    <div class="card">
                        <div class="card-body g-3">
                            <div class="table-responsive">
                                <div class="d-flex justify-content-between">
                                    <h5 class="mb-0">Item Details</h5>
                                </div>
                                <hr class="mb-2">
                                <table class="table table-bordered align-middle">
                                  <tr>
                                      <td class="text-left">Item Category </td>
                                      <td>{{$product->category}}</td>
                                  </tr>
                                  <tr>
                                      <td class="text-left">Brand</td>
                                      <td>{{$product->brand}}</td>
                                  </tr>
                                  <tr>
                                      <td class="text-left">Primary Unit</td>
                                      <td>{{$product->primary_unit}}</td>
                                  </tr>
                                  <tr>
                                      <td class="text-left">Alternative Unit</td>
                                      <td>{{$product->alternative_unit}}</td>
                                  </tr>
                                  <tr>
                                      <td class="text-left">Manage Stock</td>
                                      <td>{{$product->manage_stock}}</td>
                                  </tr>
                                  <tr>
                                      <td class="text-left">Item Type</td>
                                      <td>{{$product->item_type}}</td>
                                  </tr>
                                  <tr>
                                      <td class="text-left">Business Division</td>
                                      <td>{{$product->devisions}}</td>
                                  </tr>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card">
                        <div class="card-body g-3 row">
                            <div class="table-responsive">
                                <h5 class="mb-0">Additional Details</h5>
                                <hr class="mb-2">
                                <table class="table table-bordered align-middle">
                                  <tr>
                                      <td class="text-left">Item Short Name</td>
                                      <td>{{$product->short_name}}</td>
                                  </tr>
                                  <tr>
                                      <td class="text-left">Conversion Factor</td>
                                      <td>{{$product->convertion_factor}}</td>
                                  </tr>
                                  <tr>
                                      <td class="text-left">Short Code</td>
                                      <td>{{$product->shortcode}}</td>
                                  </tr>
                                  <tr>
                                      <td class="text-left">HSN</td>
                                      <td>{{$product->hsncode}}</td>
                                  </tr>
                                  <tr>
                                      <td class="text-left">Tax Slab</td>
                                      <td>{{$product->tax}}</td>
                                  </tr>
                                  <tr>
                                      <td class="text-left">Warehouse</td>
                                      <td>{{$product->warehouse}}</td>
                                  </tr>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4 h-100">
                    <div class="card">
                        <div class="card-body g-3 row">
                            <div class="table-responsive">
                                <h5 class="mb-2">Item Status</h5>
                                <hr class="mb-2">
                                <div class="product_statuses">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    @if(auth()->user()->can('product-prices-list'))
    <div class="col-xl-12 mx-auto">
        <div class="shadow-none radius-5 min-height">
            <div class="row">
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-body g-3" id="prices_tables">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    @endif
</div>

    <!--end row-->
@endsection
@section('js')
<script type="text/javascript" src="{{ asset('admin/plugins/datepicker/js/bootstrap-datepicker.js')}}"></script>
<script type="text/javascript">
    $(document).on('click', '.save_button', function(event){
        event.preventDefault();
        if ($('#commonModal').find('form').hasClass('update_prices')) {
            $('.error_batch').hide();
            $('.error_purchase_price').hide();
            var error = 0;

            if ($('#commonModal').find('form').find('input[name="batch"]').val().trim() == '') {
              $('.error_batch').show();
              error = 1;
              setTimeout(function () {
                $('.error_batch').hide();
                }, 3000);
            }

            if ($('#commonModal').find('form').find('input[name="purchase_price"]').val().trim() == '') {
              $('.error_purchase_price').show();
              error = 1;
              setTimeout(function () {
                $('.error_purchase_price').hide();
                }, 3000);
            }

            if ($('#commonModal').find('form').find('input[name="mrp"]').val().trim() == '') {
              $('.error_mrp').show();
              error = 1;
              setTimeout(function () {
                $('.error_mrp').hide();
                }, 3000);
            }

            $('#commonModal').find('form').find('[name="product_id"]').val("{!! $product->id !!}");

            if (error == 0) {
                let formdata = new FormData($('#commonModal').find('form')[0]);

                $.ajax({
                    url: $('#commonModal').find('form').attr('action'),
                    data: formdata,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    success: function (response) {
                        if (response.success === true) {
                          toastr.success(response.message, 'Success.');

                          // hide modal
                          $('#commonModal').modal('hide');
                          fetch_prices();
                        } else {
                            toastr.error(response.message, 'Error!');
                        }
                    }
                })
                .fail(function(jqXHR, textStatus, errorThrown) {
                    console.log('AJAX request failed:', textStatus, errorThrown);
                    toastr.error('An error occurred during the request.', 'Error!');

                    // hide modal
                    $('#commonModal').modal('hide');
                    $('#commonModal').find('.modal-body').html('');
                });
            }
        }

        error = 1;
    })
    function clickBTN() {
      $('#createLicenses').trigger('click');
    }
    $(document).ready(function(){
        fetch_prices();
        fetch_status();
    });
    function fetch_prices(){
      $.ajax({
        url:"{!! route('products.prices', $product->id) !!}",
        success:function(data){
            $('#prices_tables').html('');
            $('#prices_tables').html(data);
            $.switcher('#prices_tables .changeStatusCustom');
        }
      })
    }
    function fetch_status(){
      $.ajax({
        url:"{!! route('products.statuses', $product->id) !!}",
        success:function(data){
            $('.product_statuses').html('');
            $('.product_statuses').html(data);
            $.switcher('.product_statuses .changeStatusCustom');
        }
      })
    }

    $(document).on('click', '.prices_edit', function(){
        var id = $(this).data('id');
        var url = `{!! route('product-prices.edit', ':id') !!}`.replace(':id', id);
        $('#commonModalLabel').text('Edit Price');
        $('.save_button_span').text('Update Price');

        $.ajax({
          url:url,
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);

            $('#exp_date').datepicker().on('changeDate', function (ev) {
                   $(this).datepicker('hide');
            });
            $('#mfg_date').datepicker().on('changeDate', function (ev) {
                   $(this).datepicker('hide');
            });

          }
        })
    })

    $(document).on('click', '#createPrice', function(){
        $('#commonModalLabel').text('Add New Price');
        $('.save_button_span').text('Store Price');

        $.ajax({
          url:"{!! route('product-prices.create') !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);

            $('#exp_date').datepicker().on('changeDate', function (ev) {
                   $(this).datepicker('hide');
            });
            $('#mfg_date').datepicker().on('changeDate', function (ev) {
                   $(this).datepicker('hide');
            });
          }
        })
    })

    $(document).on('click', '.editPayment', function(){
        $('#commonModalLabel').text('Edit Payment');
        $('.save_button_span').text('Update Payment');
        var id = $(this).data('id');
        var url = `{!! route('account-payments.edit', ':id') !!}`.replace(':id', id);

        $.ajax({
          url:url,
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
          }
        })
    })

    /*********change status**********/
    $("body").on("click",'.changeStatusCustom', function(event){
          dataString       = {"id":$(this).data('id'),"status":$(this).data('status')};
          var UrlValue     = $(this).data('url');
          var status       = $(this).data('status');
          var changeStatus = $(this);
          var btn = $(this);

          Swal.fire({
              title: 'Are you sure you want to change status?',
              icon: 'warning',
              showDenyButton: true,
              showCancelButton: false,
              confirmButtonText: 'Yes',
              denyButtonText: 'No',
          }).then((result) => {
              if (result.isConfirmed) {
                  $.ajax({
                      url     : UrlValue,
                      method  : 'post',
                      data    :dataString,
                      headers:
                      {
                          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                      },
                      success : function(response){
                          if(response.success){
                              var ErroMsg = $(this).printErrorMsg(response.message);
                              $(this).Toastshow('success',ErroMsg);
                          } else {
                              var ErroMsg = $(this).printErrorMsg(response.message);
                              if (ErroMsg === '') {
                                  ErroMsg = "Something went wrong!";
                              }
                              $(this).Toastshow('error',ErroMsg);
                          }
                          fetch_status();
                          fetch_prices();
                      },
                      error: function (data) {
                          console.log("error ",data);
                          fetch_status();
                          fetch_prices();
                      }
                  });
              }
              else if (result.isDenied) {
                fetch_status();
                fetch_prices();
              }
              //return false;
          });
      //return false;
      });

    /*********delete data**********/
    $("body").on("click",'.deleteAccountData', function(event){
        dataString    = {"id":$(this).data('id')};
        var UrlValue  = $(this).data('url');
        var btn = $(this);
        //alert(dataValue);
        console.log($('meta[name="csrf-token"]').attr('content'));
        console.log(dataString);

        Swal.fire({
            title: 'Are you sure you want to delete this?',
            icon: 'warning',
            showDenyButton: true,
            showCancelButton: false,
            confirmButtonText: 'Yes',
            denyButtonText: 'No',
        }).then((result) => {
            /* Read more about isConfirmed, isDenied below */
            if (result.isConfirmed) {
                $.ajax({
                url     : UrlValue,
                method  : 'post',
                data    :{
                        "_token": $('meta[name="csrf-token"]').attr('content'),
                        "id": $(this).data('id'),
                        "account": "{!! $product->id !!}"
                },
                headers:
                {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                beforeSend: function( xhr ) {
                    // xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
                },
                success : function(response){
                    console.log(response.data);
                    if(response.success){
                        var ErroMsg = $(this).printErrorMsg(response.message);

                        $(this).Toastshow('success',ErroMsg);

                        if(btn.hasClass('address')){
                            fetch_address();
                        }
                        else if (btn.hasClass('bank')) {
                            fetch_banks();
                        }
                        else if (btn.hasClass('licenses')) {
                            fetch_licenses();
                        }
                        else if (btn.hasClass('payments')) {
                            fetch_payments();
                        } else if (btn.hasClass('attachments')) {
                            fetch_attachments();
                        }
                        console.log('s');
                    }else{
                        var ErroMsg = $(this).printErrorMsg(response.message);
                        $(this).Toastshow('error',ErroMsg);
                    }
                },
                error: function (data) {
                  console.log("error ",data);
                }
            });
            }
        });
    });
</script>
@endsection
