@extends('layouts.app')
@section('title','Products')
@section('pages')
<style type="text/css">
    .add_btn {
        height: 30px; width: 30px; border-radius: 100%; padding: 0
    }
</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" />
<link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote.min.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">Add New Product</li>
            </ol>
        </nav>
    </div>
    <div class="ms-auto">
        <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="">
                <div class="">
                    <form class="row g-3 auto-width" action="{{ route('products.store')}}" method="post" enctype='multipart/form-data' id="product_form">
                        <!-- For validation comment on -->
                        <!-- <form class="row g-3 was-validated"> -->
                        @csrf
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-body g-3 row">
                                    <h5 class="mb-0">Product Details</h5>
                                    <hr class="mb-0">
                                    <div class="col-md-12">
                                        <input type="hidden" name="redirect_url" value="{{request()->type??''}}">
                                        <div>
                                            <label for="name" class="form-label">Product / Item Name <span class="text-danger"><b>*</b></span></label>
                                        </div>
                                        <div class="input-group">
                                            <input type="text" name="name" class="form-control" value="{!! old('name') !!}" placeholder="Add NEW PRODUCT #">
                                        </div>
                                        <span class="text-danger error_name" style="display:none;">This field is required.</span>
                                    </div>
                                   
                                    {{-- <div class="col-md-12">
                                        <div>
                                            <label for="product_code" class="form-label">Product Code </label>
                                        </div>
                                        <div class="input-group">
                                            <input readonly type="text" name="product_code" class="form-control" value="{!! old('product_code') !!}" placeholder="Add NEW PRODUCT">
                                        </div>
                                        <span class="text-danger error_product_code" style="display:none;">This field is required.</span>
                                    </div> --}}
                                    <div class="col-md-12">
                                        <div>
                                            <label for="short_name" class="form-label">Product Description </label>
                                        </div>
                                        <div class="input-group">
                                            <textarea class="form-textarea" name="description" placeholder="Product Description" rows="1"></textarea>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label for="shortcode" class="form-label">Product Part No / Short Code </label>
                                        </div>
                                        <div class="input-group">
                                            <input type="text" name="shortcode" class="form-control" value="{!! old('shortcode') !!}" placeholder="Enter Product Shortcode">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label for="hsncode" class="form-label">HSN / SAC Code</label>
                                        </div>
                                        <div class="input-group">
                                            <input type="text" name="hsncode" class="form-control" value="{!! old('hsncode') !!}" placeholder="Enter Product hsncode">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label class="form-label">Tax Slab <span class="text-danger"><b>*</b></span></label>
                                        </div>
                                        <div class="input-group">
                                            <select class=" form-control" id="tax_slab_id" name="tax_slab_id" required>
                                                <option value="">--Select--</option>
                                                @foreach($tax_master as $list)
                                                <option value="{{ $list->id}}" {!! $list->default == 1 ? 'selected' : '' !!}>{{$list->name}}</option>
                                                @endforeach
                                            </select>

                                            <div class="input-group-append" style="margin: auto 10px;">
                                                <button class="btn btn-success add_btn" id="create_tax_slab" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                            </div>
                                        </div>
                                        <span class="text-danger error_tax_slab_id" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label class="form-label">Brand <span class="text-danger"><b>*</b></span></label>
                                        </div>
                                        <div class="input-group">
                                            <select class=" form-control" id="brand_id" name="brand_id" required>
                                                <option value="">--Select--</option>
                                                @foreach($brands as $list)
                                                <option value="{{ $list->id}}" {!! $list->is_default == 1 ? 'selected' : '' !!}>{{$list->name}}</option>
                                                @endforeach
                                            </select>

                                            <div class="input-group-append" style="margin: auto 10px;">
                                                <button class="btn btn-success add_btn" id="create_brand" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                            </div>
                                        </div>
                                        <span class="text-danger error_brand_id" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label class="form-label">Product Category <span class="text-danger"><b>*</b></span></label>
                                        </div>
                                        <div class="input-group">
                                            <select class=" form-control" id="category_id" name="category_id" required>
                                                <option value="">--Select--</option>
                                                @foreach($categories as $list)
                                                <option value="{{ $list->id}}" {!! $list->is_default == 1 ? 'selected' : '' !!}>{{$list->name}}</option>
                                                @endforeach
                                            </select>

                                            <div class="input-group-append" style="margin: auto 10px;">
                                                <button class="btn btn-success add_btn" id="create_category" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                            </div>
                                        </div>
                                        <span class="text-danger error_category_id" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label class="form-label">Product Salt/Group </label>
                                        </div>
                                        <div class="input-group">
                                            <select class="  form-control" id="composition_id" name="composition_id" required>
                                                <option value="">--Select--</option>
                                                @foreach($groups as $list)
                                                <option value="{{ $list->id}}" {!! $list->is_default == 1 ? 'selected' : '' !!}>{{$list->name}}</option>
                                                @endforeach
                                            </select>

                                            <div class="input-group-append" style="margin: auto 10px;">
                                                <button class="btn btn-success add_btn" id="create_group" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                            </div>
                                        </div>
                                        <span class="text-danger error_composition_id" style="display:none;">This field is required.</span>
                                    </div>

                                    <div class="col-md-6">
                                        <div>
                                            <label for="purchase_price" class="form-label">Purchase Price</label>
                                        </div>
                                        <div class="input-group">
                                            <input type="number" name="purchase_price" class="form-control" value="{!! old('purchase_price') !!}" placeholder="Enter Purchase Price">
                                        </div>
                                    </div>

                                    <div class="col-md-6">
                                        <div>
                                            <label for="wholesale_price" class="form-label">WholeSale Price</label>
                                        </div>
                                        <div class="input-group">
                                            <input type="number" name="wholesale_price" class="form-control" value="{!! old('wholesale_price') !!}" placeholder="Enter Wholesale Price">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label for="sale_price" class="form-label">Discounted/Sale Price(DP)</label>
                                        </div>
                                        <div class="input-group">
                                            <input type="number" name="sale_price" class="form-control" value="{!! old('sale_price') !!}" placeholder="Enter Sale Price">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label for="mrp" class="form-label">MRP <span class="text-danger"><b>*</b></span></label>
                                        </div>
                                        <div class="input-group">
                                            <input type="number" name="mrp" class="form-control" value="{!! old('mrp') !!}" placeholder="Enter MRP">
                                        </div>

                                        <span class="text-danger error_mrp" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label class="form-label">Primary Unit </label>
                                        </div>
                                        <div class="input-group">
                                            <select class=" form-control" id="primary_unit_id" name="primary_unit_id" required>
                                                <option value="">--Select--</option>
                                                @foreach($primary_units as $list)
                                                <option value="{{ $list->id}}" {!! $list->is_default == 1 ? 'selected' : '' !!}>{{$list->name}}</option>
                                                @endforeach
                                            </select>

                                            <div class="input-group-append" style="margin: auto 10px;">
                                                <button class="btn btn-success add_btn" id="create_primary_unit" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                            </div>
                                        </div>
                                        <span class="text-danger error_group_id" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label class="form-label">Alternative Unit </label>
                                        </div>
                                        <div class="input-group">
                                            <select class=" form-control" id="alternative_unit_id" name="alternative_unit_id" required>
                                                <option value="">--Select--</option>
                                                @foreach($alternative_units as $list)
                                                <option value="{{ $list->id}}" {!! $list->is_default == 1 ? 'selected' : '' !!}>{{$list->name}}</option>
                                                @endforeach
                                            </select>

                                            <div class="input-group-append" style="margin: auto 10px;">
                                                <button class="btn btn-success add_btn" id="create_alternative_unit" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label class="form-label">Business Division <span class="text-danger"><b>*</b></span></label>
                                        </div>
                                        <div class="input-group">
                                            <select class=" form-control" id="business_division_id" name="business_division_id" required>
                                                <option value="">--Select--</option>
                                                @foreach($business_division as $list)
                                                <option value="{{ $list->id}}" {!! request()->get('division') && request()->get('division') == 'OPD' && $list->name == 'Out Patient Department' ? 'selected' : ($list->is_default == 1 ? 'selected' : '') !!}>{{$list->name}}</option>
                                                @endforeach
                                            </select>

                                            <div class="input-group-append" style="margin: auto 10px;">
                                                <button class="btn btn-success add_btn" id="create_business_division" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                            </div>
                                        </div>
                                        <span class="text-danger error_business_division_id" style="display:none;">This field is required.</span>
                                    </div>

                                     <div class="col-md-6">
                                        <div>
                                            <label class="form-label">Product Packaging <span class="text-danger"><b>*</b></span></label>
                                        </div>
                                        <div class="input-group">
                                            <select class=" form-control" id="product_packaging_id" name="product_packaging_id" required>
                                                <option value="">--Select--</option>
                                                @foreach($product_packaging as $list)
                                                <option value="{{ $list->id}}">{{$list->name}}</option>
                                                @endforeach
                                            </select>

                                            <!-- <div class="input-group-append" style="margin: auto 10px;">
                                                <button class="btn btn-success add_btn" id="create_business_division" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                            </div> -->
                                        </div>
                                        <span class="text-danger error_product_packaging_id" style="display:none;">This field is required.</span>
                                    </div>


                                </div>
                                <div class="card-body g-3 row">
                                    <div class="col-12" align="center">
                                        <div class="d-grid gap-2 with-100">
                                          <button class="btn btn-primary save_account"  type="button"><i class="bx bx-save"></i> Save Product Details</button>
                                      </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-body g-3 row">
                                    <h5 class="mb-0">Additional Information</h5>
                                    <hr class="mb-0">
                                    <div class="col-md-6">
                                        <div>
                                            <label for="short_name" class="form-label">Product Short Name </label>
                                        </div>
                                        <div class="input-group">
                                            <input type="text" name="short_name" class="form-control" value="{!! old('short_name') !!}" placeholder="Add NEW PRODUCT">
                                        </div>
                                        <span class="text-danger error_short_name" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Main Attribute Group </label>
                                        <select class=" form-control" id="attribute_group_main" name="attribute_group_main" required>
                                            <option value="">--Select--</option>
                                            @foreach($attribute_types as $list)
                                            <option value="{{ $list->id}}" {!! $list->is_default == 1 ? 'selected' : '' !!}>{{$list->name}}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Main Attributes </label>
                                        <select class="multiple-select form-control" id="main_attribute_id" multiple name="main_attribute_id[]" required>
                                            <option value="">--Select--</option>
                                        </select>
                                    </div>

                                    <div class="col-md-6">
                                        <label class="form-label">Sub Attribute Group </label>
                                        <select class=" form-control" id="attribute_group_sub" name="attribute_group_sub" required>
                                            <option value="">--Select--</option>
                                            @foreach($attribute_types as $list)
                                            <option value="{{ $list->id}}" {!! $list->is_default == 1 ? 'selected' : '' !!}>{{$list->name}}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Sub Attributes </label>
                                        <select class=" multiple-select form-control" id="sub_attribute_id" multiple name="sub_attribute_id[]" required>
                                            <option value="">--Select--</option>
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label for="convertion_factor" class="form-label">Conversion Factor </label>
                                        </div>
                                        <div class="input-group">
                                            <input type="number" name="convertion_factor" class="form-control" value="{!! old('convertion_factor', '1') !!}">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label for="priceasper" class="form-label">Price as Per </label>
                                        </div>
                                        <div class="input-group">
                                            <select class="form-control" name="priceasper">
                                                <option value="primary">Primary Unit</option>
                                                <option value="alternative">Alternative Unit</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label for="manage_stock" class="form-label">Manage Stock</label>
                                        </div>
                                        <div class="input-group">
                                            <select class="form-control" name="manage_stock">
                                                <option value="Yes">Yes</option>
                                                <option value="No">No</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Item Type <span class="text-danger"><b>*</b></span></label>
                                        <select class=" form-control" id="item_type_id" name="item_type_id" required>
                                            <option value="">--Select--</option>
                                            @foreach($item_types as $list)
                                            <option value="{{ $list->id}}" {!! $list->is_default == 1 ? 'selected' : '' !!}>{{$list->name}}</option>
                                            {{-- <option value="{{ $list->id}}" {!! $list->is_default == 1 ? 'selected' : '' !!}>{{$list->name}}</option> --}}
                                            @endforeach
                                        </select>

                                        <span class="text-danger error_item_type_id" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Warehouse / Godown </label>
                                        <select class=" form-control" id="warehouse_id" name="warehouse_id" required>
                                            <option value="">--Select--</option>
                                            @foreach($warehouses as $list)
                                            <option value="{{ $list->id}}" {!! $list->is_default == 1 ? 'selected' : '' !!}>{{$list->name}}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Rack / Location </label>
                                        <select class=" form-control" id="location_rack_id" name="location_rack_id" required>
                                            <option value="">--Select--</option>
                                            @foreach($location_racks as $list)
                                            <option value="{{ $list->id}}" {!! $list->is_default == 1 ? 'selected' : '' !!}>{{$list->name}}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label for="min_sale_price" class="form-label">Min. Sale Price</label>
                                        </div>
                                        <div class="input-group">
                                            <input type="number" name="min_sale_price" class="form-control" value="{!! old('min_sale_price') !!}" placeholder="Min Sale Price">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label for="item_min_stock_qty" class="form-label">Min. Stock Qty</label>
                                        </div>
                                        <div class="input-group">
                                            <input type="number" name="item_min_stock_qty" class="form-control" value="{!! old('item_min_stock_qty') !!}" placeholder="Min Stock Qty">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label for="bar_code" class="form-label">Bar code</label>
                                        </div>
                                        <div class="input-group">
                                            <input type="number" name="bar_code" class="form-control" value="{!! old('bar_code') !!}" placeholder="Enter Bar Code">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label for="batch" class="form-label">Batch</label>
                                        </div>
                                        <div class="input-group">
                                            <input type="text" name="batch" class="form-control" value="{!! old('batch') !!}" placeholder="Enter batch">
                                        </div>
                                        <span class="text-danger error_batch" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label for="exp_date" class="form-label">Exp. Date</label>
                                        </div>
                                        <div class="input-group">
                                            <input type="text" name="exp_date" class="form-control" id="exp_date" value="{!! old('exp_date') !!}" placeholder="Enter exp_date">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label for="mfg_date" class="form-label">Manufacturing Date</label>
                                        </div>
                                        <div class="input-group">
                                            <input type="text" name="mfg_date" class="form-control" id="mfg_date" value="{!! old('mfg_date') !!}" placeholder="Enter mfg_date">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label for="mfg_cost" class="form-label">Manufacturing Cost</label>
                                        </div>
                                        <div class="input-group">
                                            <input type="number" name="mfg_cost" class="form-control" value="{!! old('mfg_cost') !!}" placeholder="Manufacturing Cost">
                                        </div>
                                    </div>

                                   {{-- <div class="col-md-12">
                                        <div>
                                            <label for="additional_info" class="form-label">Additional Info</label>
                                        </div>
                                        <div class="input-group">
                                            <textarea name="additional_info" id="additional_info" class="form-control" value="" placeholder="Additional Info">{!! old('additional_info') !!}</textarea>
                                        </div>
                                    </div> --}}
                                </div>
                            </div>
                        </div>
                  </form>
              </div>
          </div>
      </div>
  </div>
</div>
<!--end row-->
@endsection

@section('js')

<script type="text/javascript" src="{{ asset('admin/plugins/datepicker/js/bootstrap-datepicker.js')}}"></script>
<script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote.min.js"></script>
<script>
     $( function() {

        $('#mfg_date').datepicker();
    });
     $( function() {
        $('#exp_date').datepicker();
    });

    $("[name='name']").on('input', function() {
        const input = $(this).val();
        $("[name='short_name']").val(input);
        $("[name='shortcode']").val(input);
    });
    $("[name='name']").on('input', function() {
    const input = $(this).val();
    const uppercaseInput = input.toUpperCase().replace(/\s+/g, '_'); // Convert input to uppercase and replace spaces with underscores
    $("[name='product_code']").val(uppercaseInput);
});

    $(document).on('click','.save_account', function(e) {
        e.preventDefault();

        $('.error_name').hide();
        $('.error_tax_slab_id').hide();
        $('.error_brand_id').hide();
        $('.error_category_id').hide();
        $('.error_mrp').hide();
        $('.error_business_division_id').hide();
        $('.error_item_type_id').hide();
        var error = 0;

        if ($('input[name="name"]').val().trim() == '') {
          $('.error_name').show();
          error = 1;
          setTimeout(function () {
            $('.error_name').hide();
            }, 3000);

        }
        if ($('[name="tax_slab_id"]').val() == '') {
          $('.error_tax_slab_id').show();
          error = 1;
        }
        if ($('[name="brand_id"]').val() == '') {
          $('.error_brand_id').show();
          error = 1;
        }
        if ($('[name="category_id"]').val() == '') {
          $('.error_category_id').show();
          error = 1;
        }
        if ($('[name="mrp"]').val().trim() == '') {
          $('.error_mrp').show();
          error = 1;
          setTimeout(function () {
            $('.error_mrp').hide();
            }, 3000);

        }
        if ($('[name="business_division_id"]').val().trim() == '') {
          $('.error_business_division_id').show();
          error = 1;
          setTimeout(function () {
            $('.error_business_division_id').hide();
            }, 3000);

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

        // }
        if ($('[name="item_type_id"]').val().trim() == '') {
          $('.error_item_type_id').show();
          error = 1;
        }

        if (error == 0) {
            $('#product_form').submit();
            $('.save_account').prop('disabled', true);

        }
        error = 1;
    })

    $(document).on('change', '#attribute_group_main', function () {
        let attribute_group_id = $(this).val();

        $.ajaxSetup({
            headers : {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $.ajax({
            type: "POST",
            url: "{{ route('products.attributes') }}",
            data: {attribute_group_id:attribute_group_id},
            success: function (data) {
                $('#main_attribute_id').html(data);
            },
            error: function (data) {
                console.log(data);
            }
        });
        $.ajax({
            type: "POST",
            url: "{{ route('products.attributes_sub_group') }}",
            data: {attribute_group_id:attribute_group_id},
            success: function (data) {
                $('#attribute_group_sub').html(data);
            },
            error: function (data) {
                console.log(data);
            }
        });
    })

    $(document).on('change', '#attribute_group_sub', function () {
        let attribute_group_id = $(this).val();

        $.ajaxSetup({
            headers : {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $.ajax({
            type: "POST",
            url: "{{ route('products.attributes') }}",
            data: {attribute_group_id:attribute_group_id},
            success: function (data) {
                $('#sub_attribute_id').html(data);
            },
            error: function (data) {
                console.log(data);
            }
        });
    })

    $(document).on('click', '#create_tax_slab', function(){
        $('#commonModalLabel').text('Add New Tax Master');
        $('.save_button_span').text('Save Tax Master');
        $.ajax({
          url:"{!! route('tax-masters.create') !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
          }
        })
    })

    $(document).on('click', '#create_brand', function(){
        $('#commonModalLabel').text('Add New Product Brands');
        $('.save_button_span').text('Save Product Brands');
        $.ajax({
          url:"{!! route('product-brands.create') !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
          }
        })
    })

    $(document).on('click', '#create_category', function(){
        $('#commonModalLabel').text('Add New Product Categories');
        $('.save_button_span').text('Save Product Categories');
        $.ajax({
          url:"{!! route('product-categories.create') !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
          }
        })
    })

    $(document).on('click', '#create_group', function(){
        $('#commonModalLabel').text('Add New Product Group');
        $('.save_button_span').text('Save Product Group');
        $.ajax({
          url:"{!! route('product-groups.create') !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
          }
        })
    })

    $(document).on('click', '#create_primary_unit', function(){
        $('#commonModalLabel').text('Add New Primary Unit');
        $('.save_button_span').text('Save Primary Unit');
        $.ajax({
          url:"{!! route('primary-units.create') !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
          }
        });
    });

    $(document).on('click', '#create_alternative_unit', function(){
        $('#commonModalLabel').text('Add New Alternative Units');
        $('.save_button_span').text('Save Alternative Units');
        $.ajax({
          url:"{!! route('product-alternative-units.create') !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
          }
        })
    })

    $(document).on('click', '#create_business_division', function(){
        $('#commonModalLabel').text('Add New Business Division');
        $('.save_button_span').text('Save Business Division');
        $.ajax({
          url:"{!! route('business-divisions.create') !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
          }
        })
    })

    $(document).on('click', '.save_button', function(event){
        event.preventDefault();
        var error = 0;

        if ($('#commonModal').find('form').hasClass('tax_master')) {
            $('.name').hide();
            $('.calculation').hide();
            $('.total_percentage').hide();
            $('.description').hide();
            $('.priority').hide();

            if ($('#commonModal').find('form').find('input[name="name"]').val().trim() == '') {
              $('.error_name').show();
              error = 1;
            }
            if ($('#commonModal').find('form').find('input[name="total_percentage"]').val().trim() == '') {
              $('.error_total_percentage').show();
              error = 1;
            }

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

                $.ajax({
                    url: "{!! route('tax-masters.store') !!}",
                    data: formdata,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    success: function (response) {
                        if (response.success === true) {
                            toastr.success(response.message, 'Success.');
                            // append new category to selection
                            $('[name="tax_slab_id"]').append(`<option value="${response.data.id}" selected>${response.data.name}</option>`);
                            $('[name="tax_slab_id"]').trigger('change');

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                        } 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('');
                    $('#commonModal').removeClass('category');
                });
            }
            error = 1;
        }
        else if ($('#commonModal').find('form').hasClass('brand')) {
            $('.error_name').hide();

            if ($('#commonModal').find('form').find('input[name="name"]').val().trim() == '') {
              $('.error_name').show();
              error = 1;
            }

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

                $.ajax({
                    url: "{!! route('product-brands.store') !!}",
                    data: formdata,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    success: function (response) {
                        if (response.success === true) {
                            toastr.success(response.message, 'Success.');
                            // append new category to selection
                            $('[name="brand_id"]').append(`<option value="${response.data.id}" selected>${response.data.name}</option>`);
                            $('[name="brand_id"]').trigger('change');

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                        } 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('');
                    $('#commonModal').removeClass('category');
                });
            }
        }
        else if ($('#commonModal').find('form').hasClass('category')) {
            $('.error_name').hide();

            if ($('#commonModal').find('form').find('input[name="name"]').val().trim() == '') {
              $('.error_name').show();
              error = 1;
            }

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

                $.ajax({
                    url: "{!! route('product-categories.store') !!}",
                    data: formdata,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    success: function (response) {
                        if (response.success === true) {
                            toastr.success(response.message, 'Success.');
                            // append new category to selection
                            $('[name="category_id"]').append(`<option value="${response.data.id}" selected>${response.data.name}</option>`);
                            $('[name="category_id"]').trigger('change');

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                        } 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('');
                    $('#commonModal').removeClass('category');
                });
            }
        }
        else if ($('#commonModal').find('form').hasClass('group')) {
            $('.error_name').hide();

            if ($('#commonModal').find('form').find('input[name="name"]').val().trim() == '') {
              $('.error_name').show();
              error = 1;
            }

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

                $.ajax({
                    url: "{!! route('product-groups.store') !!}",
                    data: formdata,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    success: function (response) {
                        if (response.success === true) {
                            toastr.success(response.message, 'Success.');
                            // append new category to selection
                            $('[name="composition_id"]').append(`<option value="${response.data.id}" selected>${response.data.name}</option>`);
                            $('[name="composition_id"]').trigger('change');

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                        } 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('');
                    $('#commonModal').removeClass('category');
                });
            }
        }
        else if ($('#commonModal').find('form').hasClass('primary_unit')) {
            $('.error_name').hide();

            if ($('#commonModal').find('form').find('input[name="name"]').val().trim() == '') {
              $('.error_name').show();
              error = 1;
            }

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

                $.ajax({
                    url: "{!! route('primary-units.store') !!}",
                    data: formdata,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    success: function (response) {
                        if (response.success === true) {
                            toastr.success(response.message, 'Success.');
                            // append new category to selection
                            $('[name="primary_unit_id"]').append(`<option value="${response.data.id}" selected>${response.data.name}</option>`);
                            $('[name="primary_unit_id"]').trigger('change');

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                        } 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('');
                    $('#commonModal').removeClass('category');
                });
            }
        }
        else if ($('#commonModal').find('form').hasClass('alternative_units')) {
            $('.error_name').hide();

            if ($('#commonModal').find('form').find('input[name="name"]').val().trim() == '') {
              $('.error_name').show();
              error = 1;
            }

            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.');
                            // append new category to selection
                            $('[name="alternative_unit_id"]').append(`<option value="${response.data.id}" selected>${response.data.name}</option>`);
                            $('[name="alternative_unit_id"]').trigger('change');

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                        } 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('');
                    $('#commonModal').removeClass('category');
                });
            }
        }
        else if ($('#commonModal').find('form').hasClass('business-divisions')) {
            $('.error_code').hide();
            $('.error_name').hide();

            if ($('#commonModal').find('form').find('input[name="name"]').val().trim() == '') {
              $('.error_name').show();
              error = 1;
            }

            if ($('#commonModal').find('form').find('input[name="code"]').val().trim() == '') {
              $('.error_code').show();
              error = 1;
            }

            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.');
                            // append new category to selection
                            $('[name="business_division_id"]').append(`<option value="${response.data.id}" selected>${response.data.name}</option>`);
                            $('[name="business_division_id"]').trigger('change');

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                        } 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('');
                    $('#commonModal').removeClass('category');
                });
            }
        }
    })
    $(document).ready(function() {
        $('#additional_info').summernote();
    });
</script>
@endsection
