@extends('layouts.app')
@section('title')@lang('quickadmin.inventory.title')@endsection
@section('customCss')
<meta name="csrf-token" content="{{ csrf_token() }}" >
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />

@endsection

@section('main-content')
<style type="text/css">
 
</style>
<div class="card MainBox">
    <div class="mainHeading">
        <h4>@lang('quickadmin.inventory.title')</h4>
        <div class="top_both_btn">
            <a href="javascript:void(0)" class="btn addShiftingGoods addBtn" title="@lang('quickadmin.inventory.shifting_goods')"><i class="fas fa-plus"></i>@lang('quickadmin.inventory.shifting_goods')</a>
            @can('inventory_create')
            <a href="javascript:void(0)" class="btn addRecordBtn addBtn"  data-href="{{ route('inventory.create')}}" title="@lang('quickadmin.inventory.add')"><i class="fas fa-plus"></i> @lang('quickadmin.inventory.add')</a>
            @endcan
        </div>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive fixed_Search inventory-table">
            {{$dataTable->table(['class' => 'table dt-responsive', 'style' => 'width:100%;','id'=>'dataaTable'])}}
        </div>
    </div>
</div>
<div class="popup_render_div"></div>


<!-- Add Edit Modal -->
  <div class="modal fade px-2" id="shiftingGoodsModal" tabindex="-1" role="dialog" aria-labelledby="shiftingGoodsModalTitle" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLongTitle">@lang('quickadmin.inventory.shifting_goods')</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <form id="shiftingGoodsForm">
          <div class="modal-body floatingLabel">
            <div class="row">
                <div class="col-sm-6 col-md-6 fullselect2">
                    <div class="form-group">
                        <label for="shift_product_id">@lang('quickadmin.inventory.fields.product_id')<span class="text-danger">*</span></label>
                        <div class="input-group">
                            <select name="product_id" class="form-control select2 shiftProduct" id="shift_product_id">
                                <option value=" " disabled selected>@lang('quickadmin.inventory.select_product')</option>
                                @foreach($allproduct as $product)
                                    <option value="{{ $product->id }}"  {{ isset($inventory) ? $inventory->product_id == $product->id ? 'selected' :'' :'' }} >{{ $product->full_name ??'' }} </option>
                                @endforeach
                            </select>
                        </div>
                       
                    </div>
                </div>
                <div class="col-sm-6 col-md-6">
                    <div class="form-group">
                        <label for="shift_entry_date">@lang('quickadmin.inventory.fields.ship_date')<span class="text-danger">*</span></label>
                        <div class="input-group">
                            <input type="text" class="form-control" name="entry_date" max="<?= date('Y-m-d'); ?>" value="{{ isset($inventory) ? $inventory->entry_date : old('entry_date') }}" id="shift_entry_date" >
                        </div>
                    </div>
                </div>

                <div class="col-sm-6 col-md-6">
                    <div class="form-group">
                        <label for="from">@lang('quickadmin.inventory.fields.from')<span class="text-danger">*</span></label>
                        <div class="input-group">
                            <select name="from" class="form-control select2" id="from">
                                <option value="" selected>@lang('quickadmin.inventory.select_location_from')</option>
                                @foreach(config('app.product_place') as $key => $place)
                                    <option value="{{ $key }}" {{ isset($inventory) && $inventory->place == $key ? 'selected' : '' }}>
                                        {{ $place ?? '' }}
                                    </option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                </div>  
                <div class="col-sm-6 col-md-6">
                    <div class="form-group">
                        <label for="to">@lang('quickadmin.inventory.fields.to')<span class="text-danger">*</span></label>
                        <div class="input-group">
                            <select name="to" class="form-control select2" id="to">
                                <option value="" selected>@lang('quickadmin.inventory.select_location_to')</option>
                                @foreach(config('app.product_place') as $key => $place)
                                    <option value="{{ $key }}" {{ isset($inventory) && $inventory->place == $key ? 'selected' : '' }}>
                                        {{ $place ?? '' }}
                                    </option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                </div>
                
                <div class="col-sm-6 col-md-6">
                    <div class="form-group">
                        <label for="code">@lang('quickadmin.inventory.fields.quantity')<span class="text-danger">*</span></label>
                        <div class="input-group">                            
                            <input type="text" class="form-control" name="quantity" value="{{ isset($inventory) ? (int)$inventory->quantity : old('quantity') }}" id="quantity" min="1" step="1" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); if(this.value.includes('-')) this.value = this.value.replace('-', ''); if(this.value.indexOf('.') !== -1) { var parts = this.value.split('.'); this.value = parts[0] + '.' + parts[1].slice(0, 2); }" placeholder="@lang('quickadmin.qa_enter') @lang('quickadmin.inventory.fields.quantity')">
                        </div>
                    </div>
                </div>
            </div>
          </div>
          <div class="modal-footer pt-0">
            <div class="success_error_message"></div>
            <button type="submit" class="btn btn-primary save_btn m-0" title="Submit">@lang('quickadmin.qa_submit')</button>
          </div>
        </form>
      </div>
    </div>
  </div>
<!-- Add Edit Modal -->
@endsection


@section('customJS')
{!! $dataTable->scripts() !!}
<script src="{{ asset('admintheme/assets/bundles/datatables/datatables.min.js') }}"></script>
<script src="{{ asset('admintheme/assets/bundles/datatables/DataTables-1.10.16/js/dataTables.bootstrap4.min.js') }}"></script>
<script src="{{ asset('admintheme/assets/bundles/jquery-ui/jquery-ui.min.js') }}"></script>
<!-- Page Specific JS File -->
<script src="{{ asset('admintheme/assets/js/page/datatables.js') }}"></script>
<script src="{{ asset('admintheme/assets/js/moment.min.js') }}"></script>
<script src="{{ asset('admintheme/assets/js/daterangepicker.min.js') }}"></script>


<script>
$(document).ready(function () {

    var DataaTable = $('#dataaTable').DataTable();

    $(document).on('click','.addRecordBtn', function(e){
        e.preventDefault();
        var hrefUrl = $(this).attr('data-href');
        $.ajax({
            type: 'get',
            url: hrefUrl,
            dataType: 'json',
            beforeSend: function () {
                showLoader();
            },
            success: function (response) {
                if(response.success) {
                    $('.popup_render_div').html(response.htmlView);
                    $('#inventoryAddModal').modal('show');
                    $('#product_id, #place').select2({
                        dropdownParent: $('.popup_render_div #inventoryAddModal'),
                        placeholder: "Select Product",
                        width: '100%',
                        dropdownParent: $('#inventoryAddModal')
                    });
                    initializeEntryDatePicker();                                        
                }
            },
            complete: function () {
                hideLoader();
            },
        });
    });
    $(document).on("click", ".edit-inventory-btn", function (e) {
        e.preventDefault();
        var hrefUrl = $(this).attr('data-href');
        $.ajax({
            type: 'get',
            url: hrefUrl,
            dataType: 'json',
            beforeSend: function () {
                showLoader();
            },
            success: function (response) {
                if(response.success) {
                    $('.popup_render_div').html(response.htmlView);
                    $('#inventoryEditModal').modal('show');
                    $('#product_id, #place').select2({
                        dropdownParent: $('.popup_render_div #inventoryEditModal') // Set the dropdown parent to the modal
                    });
                    initializeEntryDatePicker(response.entry_date);                   
                }
            },
            complete: function () {
                hideLoader();
            },
        });
    });


    $(document).on('submit', '#AddForm', function (e) {
        e.preventDefault();
        showLoader();
        $("#AddForm button[type=submit]").prop('disabled',true);
        $(".error").remove();
        $(".is-invalid").removeClass('is-invalid');
        var formData = $(this).serialize();
        var formAction = $(this).attr('action');

        $.ajax({
            url: formAction,
            type: 'POST',
            headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            data: formData,
            success: function (response) {
                hideLoader();
                var alertType = response['alert-type'];
                var message = response['message'];
                var title = response['title'];
                $("#AddForm button[type=submit]").prop('disabled',false);
                $('#AddForm')[0].reset();
                $('#inventoryAddModal').modal('hide');
                showToaster(title,alertType,message);
                DataaTable.ajax.reload();
            },
            error: function (xhr) {
                hideLoader();
                $("#AddForm button[type=submit]").prop('disabled',false);
                var errors= xhr.responseJSON.errors;
                for (const elementId in errors) {
                    //$("#"+elementId).addClass('is-invalid');
                    var errorHtml = '<div><span class="error text-danger">'+errors[elementId]+'</span></div>';
                    $(errorHtml).insertAfter($("#"+elementId).parent());
                }
            }
        });

    });

    $(document).on('change', '#product_id', function () {
        $(this).removeClass('is-invalid');
        $(this).closest('.form-group').find('.error').remove();
    });

    $(document).on('submit', '#EditForm', function (e) {
        e.preventDefault();
        $("#EditForm button[type=submit]").prop('disabled',true);
        $(".error").remove();
        $(".is-invalid").removeClass('is-invalid');
        var formData = $(this).serialize();
        var formAction = $(this).attr('action');

        $.ajax({
            url: formAction,
            type: 'PUT',
            headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            data: formData,
            success: function (response) {
                showLoader();
                var alertType = response['alert-type'];
                var message = response['message'];
                var title = response['title'];
                $("#EditForm button[type=submit]").prop('disabled',false);
                $('#EditForm')[0].reset();
                $('#inventoryEditModal').modal('hide');
                showToaster(title,alertType,message);
                DataaTable.ajax.reload();
            },
            complete: function () {
                hideLoader();
            },
            error: function (xhr) {
                hideLoader();
                $("#EditForm button[type=submit]").prop('disabled',false);
                var errors= xhr.responseJSON.errors;
                for (const elementId in errors) {
                  //  $("#"+elementId).addClass('is-invalid');
                    var errorHtml = '<div><span class="error text-danger">'+errors[elementId]+'</span></div>';
                    $(errorHtml).insertAfter($("#EditForm #"+elementId).parent());
                }
            }
        });
    });

    $(document).on('click', '.delete-inventory-btn', function(e) {
        e.preventDefault();
        var hrefUrl = $(this).attr('data-href');
        swal({
            title: "{{ trans('messages.deletetitle') }}",
            text: "{{ trans('messages.areYouSure') }}",
            icon: 'warning',
            buttons: {
            confirm: "{{ trans('quickadmin.qa_delete') }}",
            cancel: "{{ trans('quickadmin.qa_cancel') }}",
            },
            dangerMode: true,
        }).then((willDelete) => {
            if (willDelete) {
                $.ajax({
                url: hrefUrl,
                type: 'DELETE',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                success: function (response) {
                    var alertType = response['alert-type'];
                        var message = response['message'];
                        var title = response['title'];
                        showToaster(title,alertType,message);
                        DataaTable.ajax.reload();
                },
                error: function (xhr) {
                    swal("{{ trans('quickadmin.inventory.inventory') }}", 'Something went wrong', 'error');
                }
                });
            }
        });
    }); 
    

    $(document).on("click", ".view-inventory-btn", function (e) {
        e.preventDefault();
        var hrefUrl = $(this).attr('data-href');
        $.ajax({
            type: 'get',
            url: hrefUrl,
            dataType: 'json',
            beforeSend: function () {
                showLoader();
            },
            success: function (response) {
                if(response.success) {
                    $('.popup_render_div').html(response.htmlView);
                    $('#inventoryViewModal').modal('show');                  
                }
            },
            complete: function () {
                hideLoader();
            },
        });
    });

    function initializeEntryDatePicker(entryDate = null) {
        const dateFormat = "{{ config('constant.js_date_format.date') }}";
        $('#entry_date,#shift_entry_date').daterangepicker({
            locale: { format: dateFormat },
            singleDatePicker: true,
            autoUpdateInput: true,
            autoApply: true,
            startDate:  entryDate ? moment(entryDate) : moment(),
            maxDate: moment()
        });
    }

    $(document).on('change input', '#quantity, #from, #to, #shift_product_id', function(){
        $(this).closest('.form-group').find('.error.text-danger').remove();
    });

    $(document).on('click','.addShiftingGoods',function(e){
        e.preventDefault();
        $.ajax({
            type: "GET",
            url: "{{ route('all-products') }}",
            beforeSend: function(){
                $('.error').html('');
                showLoader();
            },
            success: function(data) {
                $("#shiftingGoodsModal").modal('show');
                $('#shiftingGoodsModal .availability-text').remove();
                $("#shift_product_id").empty();
                $("#shift_product_id").append('<option value="" selected>Select Product</option>');
                $.each(data.allproduct, function (key, value) {
                    $("#shift_product_id").append('<option value="' + value.id + '">' + value.name + '</option>');
                });
                $('#quantity').val("");
                initializeEntryDatePicker(); 
            },
            complete: function () {
                hideLoader();
            },
        });
    });

    $('#shift_product_id').select2({
        placeholder: "Select Product",
        width: '100%',
        dropdownParent: $('#shiftingGoodsModal')
    });
    $('#from').select2({
        placeholder: "Location From",
        width: '100%',
        dropdownParent: $('#shiftingGoodsModal')
    }).on('change', function() {
        let selectedQty = $(this).find(':selected').data('qty');
        $('#quantity').attr('max', selectedQty); 
    });
    
    $('#to').select2({
        placeholder: "Location To",
        width: '100%',
        dropdownParent: $('#shiftingGoodsModal')
    });

    let allOptions = @json(config('app.product_place'));
    function refreshOptions(excludeVal, targetSelect) {
        let select = $(targetSelect);
        let currentVal = select.val();
        select.empty();

        $.each(allOptions, function (key, text) {
            if (key != excludeVal) {
                select.append(new Option(text, key));
            }
        });
        if (currentVal && currentVal !== excludeVal) {
            select.val(currentVal);
        } else {
            select.prop("selectedIndex", 0);
        }
    }

    $(document).on("change", "#from", function () {
        let val = $(this).val();
        if (!val) {
            $('#to').prop('disabled', true).empty().append('<option value="">Select Location To</option>');
        } else {
            $('#to').prop('disabled', false);
            refreshOptions(val, "#to");
        }
    });

    $(document).on('submit', '#shiftingGoodsForm', function(e) {
        e.preventDefault();
        showLoader();
        $("#shiftingGoodsForm button[type=submit]").prop('disabled', true);
        $(".error").remove();
        $(".is-invalid").removeClass('is-invalid');

        let maxQty = parseInt($('#from option:selected').data('qty')) || 0;
        let enteredQty = parseInt($('#quantity').val()) || 0;

        if (enteredQty > maxQty) {
            hideLoader();
            $("#shiftingGoodsForm button[type=submit]").prop('disabled', false);
            swal("{{ trans('quickadmin.inventory.shifting_goods') }}", "Insufficient stock! Maximum available quantity is " + maxQty, 'error');
            return; 
        }

        $.ajax({
            url: "{{ route('inventory.shifting-goods.store') }}",
            type: "POST",
            data: $(this).serialize(),
            success: function(response) {
                showLoader();
                var alertType = response['alert-type'];
                var message = response['message'];
                var title = response['title'];

                showToaster(title, alertType, message);

                $('#shiftingGoodsForm button[type=submit]').prop('disabled', false);
                $('#shiftingGoodsForm')[0].reset();
                $('#shiftingGoodsModal').modal('hide');

                if (typeof DataaTable !== "undefined") {
                    DataaTable.ajax.reload();
                }
            },
            complete: function () {
                hideLoader();
            },
            error: function(xhr) {
                hideLoader();
                $('#shiftingGoodsForm button[type=submit]').prop('disabled', false);

                if (xhr.responseJSON && xhr.responseJSON.errors) {
                    var errors = xhr.responseJSON.errors;
                    for (const elementId in errors) {
                        var errorHtml = '<div><span class="error text-danger">'+errors[elementId][0]+'</span></div>';
                        let fieldId = (elementId === 'product_id') ? 'shift_product_id' : elementId;
                        $("#" + fieldId).closest('.form-group').append(errorHtml);
                    }
                } else {
                    swal("{{ trans('quickadmin.inventory.shifting_goods') }}", 'Something Went Wrong!', 'error');
                }
            }
        });
    });

    $(document).on('change', '#shift_product_id', function(e) {
        e.preventDefault();
        $('.availability-text').remove();
        if (!$('#shift_product_id').val()) return;
        showLoader();
        $.ajax({
            url: "{{ route('orders.getStockAvailability') }}",
            type: "POST",
            data: {
                product_id : $('#shift_product_id').val()
            },
            success: function(response) { 
                showLoader();
                let fromSelect = $('#from');
                fromSelect.empty();
                fromSelect.append('<option value="" selected>Select Location From</option>');
                $('#to').prop('disabled', true).empty().append('<option value="">Select Location To</option>');
                $.each(response.inventory, function(place, quantity) {
                    if (quantity > 0) {
                        fromSelect.append('<option value="'+place+'" data-qty="'+quantity+'">'+allOptions[place]+'</option>');
                    }
                });

                var $modal = $(e.target).closest('.modal'); 
                var modalId = $modal.attr('id'); 
                // $modal.find('.error').remove();
                if (modalId === 'shiftingGoodsModal') {
                    var stockCountString = '<div class="text-danger font-weight-bold availability-text">' + response.message + '</div>';
                    $modal.find('#shift_product_id').parent().after(stockCountString);
                }
   
            },
            complete: function () {
                hideLoader();
            },
            error: function(xhr) {
               $("#place").val("");
                $("#quantity").val("");
            }
        });
    });
});
</script>
@endsection
