@extends('layouts.app')
@section('title', 'Warehouse')
@section('pages')
    <style type="text/css">
        .add_btn {
            height: 30px;
            width: 30px;
            border-radius: 100%;
            padding: 0
        }

        .intl-tel-input {
            width: 100%;
        }

        .account_title {
            width: 50px;
            border: 1px solid #ced4da;
            border-top-left-radius: 4px;
            border-bottom-left-radius: 4px;
        }
    </style>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.10/css/intlTelInput.css">
    <!--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> Warehouse</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 Warehouse</li>
                </ol>
            </nav>
        </div>
        <div class="ms-auto">
            <div class="btn-group">
                <a href="{{route('product-warehouse.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('product-warehouse.store') }}" method="post"
                            enctype='multipart/form-data' id="account_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">Warehouse Details</h5>
                                        <hr class="mb-0">
                                        <div class="col-md-12">
                                            <label for="name" class="form-label">Name <span
                                                    class="text-danger"><b>*</b></span></label>
                                            <input type="text" class="form-control" id="name" name="name"
                                                aria-describedby="inputGroupPrepend">
                                            <span class="text-danger error_name" style="display:none;">This field is required.</span>
                                        </div>
                                        <div class="col-md-6">
                                            <label for="trade_name" class="form-label">Trade Name <span class="text-danger"><b>*</b></span></label>
                                            <input type="text" class="form-control" id="trade_name" name="trade_name" aria-describedby="inputGroupPrepend"> <span class="text-danger error_trade_name" style="display:none;">This field is required.</span>
                                        </div>
                                        <div class="col-md-6">
                                            <label for="company_id" class="form-label">Company <span class="text-danger"><b>*</b></span></label>
                                            <select class="form-control" name="company_id">
                                                @foreach ($company as $list)
                                                    <option value="{{ $list->id }}">{{ $list->name }}</option>
                                                @endforeach
                                            </select>
                                            <span class="text-danger error_company_id" style="display:none;">This field is required.</span>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">Country</label>
                                            <select class="form-control" id="country" name="country_id" onchange="changecontry()" required>
                                                <option value=""> Select Country</option>
                                                @foreach($country as $list)
                                                <option value="{{ $list->id}}" {!! old('country_id', ($company_address->country_id ?? '')) == $list->id ? 'selected' : '' !!}
                                                        {!! $company_address['country_id']?($company_address['country_id']==$list->id?'selected':''):'' !!}>{{$list->name}}</option>
                                                @endforeach
                                            </select>
                                            <span class="text-danger error_country_id" style="display:none;">This field is required.</span>
                                        </div>

                                        <div class="col-md-6">
                                            <label class="form-label">State</label>
                                            <input type="hidden" value="@if(isset($company_address['state_id'])){{$company_address['state_id']}}@endif" id="stateid">
                                            <select class="form-control" name="state_id" id="states">
                                            </select>
                                            <span class="text-danger error_state_id" style="display:none;">This field is required.</span>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">City</label>
                                            {{-- @dd($company_address['city_id']); --}}
                                            <input type="hidden" value="@if(isset($company_address['city_id'])){{$company_address['city_id']}}@endif" name="cityid">
                                            <select class="form-control" name="city_id" id="cities">
                                            </select>
                                            <span class="text-danger error_city_id" style="display:none;">This field is required.</span>
                                        </div>
                                        <div class="col-md-6">
                                            <label for="address_1" class="form-label">Address 1</label>
                                            <textarea class="form-control" id="address_1" name="address_1"></textarea>
                                        </div>
                                        <div class="col-md-6">
                                            <label for="address_2" class="form-label">Address 2</label>
                                            <textarea class="form-control" id="address_2" name="address_2"></textarea>
                                        </div>
                                        <div class="col-md-6">
                                            <label for="place" class="form-label">Place </label>
                                            <input type="text" class="form-control" id="place" name="place" aria-describedby="inputGroupPrepend">
                                            <span class="text-danger error_place" style="display:none;">This field is required.</span>
                                        </div>
                                        <div class="col-md-6">
                                            <label for="gst_no" class="form-label">GST NO</label>
                                            <input type="number" class="form-control" id="gst_no" name="gst_no" aria-describedby="inputGroupPrepend">
                                            <span class="text-danger error_gst_no" style="display:none;">This field is required.</span>
                                        </div>

                                    </div>

                                    <div class="card-body g-3 row additional_fields">
                                    </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="submit"><i
                                                        class="bx bx-save"></i> Save Account Details</button>
                                            </div>
                                        </div>
                                    </div>

                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!--end row-->
@endsection

@section('js')
    <script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.10/js/intlTelInput.js"></script>

    <script src="{!! asset('admin/js/accounts.js') !!}"></script>
    <script>
        $('.single-select-clients').select2({
            theme: 'bootstrap4',
            width: $(this).data('width') ? $(this).data('width') : $(this).hasClass('w-100') ? '100%' : 'style',
            placeholder: $(this).data('placeholder'),
            allowClear: Boolean($(this).data('allow-clear')),
            ajax: {
                url: "{!! route('product-warehouse.country') !!}",
                dataType: 'json',
                delay: 250,
                processResults: function(data) {
                    return {
                        results: $.map(data, function(item) {
                            return {
                                text: item.name,
                                id: item.id
                            }
                        })
                    };
                },
                cache: true
            }
        });
        $('.single-select-clients').trigger('change');
        var telInput = $('#phone_no , #whatsapp_no');


        function allNumeric(inputtxt) {
            onlyNumbers = inputtxt.replace(/[^0-9]/g, '');
            if (onlyNumbers.length > 16) {
                onlyNumbers = onlyNumbers.substring(0, 16);
            }
            return onlyNumbers;
        }
        $("[name='opening_balance']").on('input', function() {
            const onlyNumbers = allNumericDecimal($(this).val());
            $("[name='opening_balance']").val(onlyNumbers);
        });

        function allNumericDecimal(inputtxt) {
            onlyNumbers = inputtxt.replace(/[^0-9.]/g, '');
            return onlyNumbers;
        }

        $("[name='name']").on('input', function() {
            const input = $(this).val();
            $("[name='print_name']").val(input);
        });

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

            // if ($('#name').val().trim() != '') {
            //     var dailcode_title = $('.phone_no_col .selected-flag').attr('title');
            //     var dailcode_array = dailcode_title.split("+");
            //     $('input[name="phone_no"]').val("+" + dailcode_array[1] + $('#phone_no').val());
            // }

            // if ($('#trade_name').val().trim() != '') {
            //     var dailcode_title = $('.whatsapp_no_col .selected-flag').attr('title');
            //     var dailcode_array = dailcode_title.split("+");
            //     $('input[name="trade_name"]').val("+" + dailcode_array[1] + $('#trade_name').val());
            // }

            $('.error_name').hide();
            $('.error_trade_name').hide();
            var error = 0;


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

            if (error == 0) {
                let formdata = new FormData($('#account_form')[0]);

                $.ajax({
                        url: "{{ route('product-warehouse.store') }}",
                        data: formdata,
                        processData: false,
                        contentType: false,
                        type: 'POST',
                        success: function(response) {
                            if (response.success === true) {
                                toastr.success(response.message, 'Success.');
                                setTimeout(window.location.href = "{!! route('product-warehouse.index') !!}", 3000);
                            } 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!');
                    });
            }
            error = 1;
        })
        $(document).ready(function() {
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': jQuery('meta[name="csrf-token"]').attr('content')
                }
            });
            changecontry();
            $('#states').trigger('change');

        });

        function changecontry()
        {
            $.ajaxSetup({
                headers : {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            let country=$('#country').val();
            let stateid=$('#stateid').val();

            $.ajax({
                type: "POST",
                url: "{{ url('companies/getstate') }}",
                data: {country:country,stateid:stateid},
                success: function (data) {
                    $('#states').html(data);
                    $('#states').trigger('change');
                },
                error: function (data) {
                    console.log(data);
                }
            });
            $.ajax({
                type: "POST",
                url: "{{ url('companies/getcountrycode') }}",
                data: {
                    country: country
                },
                success: function (countryCode) {
                    var telInput = $('#phone_no, #whatsapp_no, #alternative_no');

                    // Destroy the existing instances
                    telInput.intlTelInput('destroy');

                    // Reinitialize the input fields with the new country code
                    telInput.intlTelInput({
                        utilsScript: 'https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.13/js/utils.js',
                        initialCountry: countryCode, // Set the received country code directly
                        separateDialCode: true
                    });
                },
                error: function (data) {
                    // Handle error
                }
            });
        }

        $(document).on('change', '#states', function () {
            let states_id=$('#states').val()?$('#states').val():"{{isset($company_address->state_id) ? $company_address->state_id : ''}}";
            let cityid=$('#cityid').val();

            $.ajaxSetup({
                headers : {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });
            $.ajax({
                type: "POST",
                url: "{{ url('companies/getcity') }}",
                data: {states_id:states_id,cityid:cityid},
                success: function (data) {
                    $('#cities').html(data);
                },
                error: function (data) {
                    console.log(data);
                }
            });
        })

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

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

        // $(document).on('click', '#create_account_type', function() {
        //     $('#commonModalLabel').text('Add New Account Type');
        //     $('.save_button_span').text('Save Account Type');
        //     $.ajax({
        //         url: "{!! route('account-types.create') !!}",
        //         success: function(data) {
        //             $('#commonModal').find('.modal-body').html('');
        //             $('#commonModal').find('.modal-body').html(data);
        //         }
        //     })
        // })

        $(document).on('click', '#create_tax_register_categories', function() {
            $('#commonModalLabel').text('Add New Category');
            $('.save_button_span').text('Save Category');
            $.ajax({
                url: "{!! route('tax-register-categories.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('accounting-groups')) {
                $('.error_name').hide();
                var error = 0;

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

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

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

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

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

                    $.ajax({
                            url: "{!! route('accounting-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="accounting_group_id"]').append(
                                        `<option value="${response.data.id}" selected>${response.data.name}</option>`
                                        );
                                    $('[name="accounting_group_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('account-category')) {

                $('.error_category_name').hide();
                $('.error_category_code').hide();
                $('.error_prefix').hide();
                var error = 0;

                if ($('#commonModal').find('form').find('input[name="category_name"]').val().trim() == '') {
                    $('#commonModal').find('.error_category_name').show();
                    error = 1;
                }
                if ($('#commonModal').find('form').find('input[name="category_code"]').val().trim() == '') {
                    $('#commonModal').find('.error_category_code').show();
                    error = 1;
                }
                if ($('#commonModal').find('form').find('input[name="prefix"]').val().trim() == '') {
                    $('#commonModal').find('.error_prefix').show();
                    error = 1;
                }

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

                    $.ajax({
                            url: "{{ route('account-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="account_category_id"]').append(
                                        `<option value="${response.data.id}" selected>${response.data.category_name}</option>`
                                        );
                                    $('[name="account_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('');
                        });
                }
            } else if ($('#commonModal').find('form').hasClass('account-type')) {
                $('.error_enquiry_source_name').hide();
                $('.error_enquiry_source_code').hide();
                $('.error_enquiry_source_priority').hide();

                if ($('#commonModal').find('form').find('input[name="type_name"]').val().trim() == '') {
                    $('#commonModal').find('.error_type_name').show();
                    error = 1;
                }
                if ($('#commonModal').find('form').find('input[name="type_code"]').val().trim() == '') {
                    $('#commonModal').find('.error_type_code').show();
                    error = 1;
                }
                if ($('#commonModal').find('form').find('input[name="prefix"]').val().trim() == '') {
                    $('#commonModal').find('.error_prefix').show();
                    error = 1;
                }

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

                    $.ajax({
                            url: "{{ route('account-types.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="account_type_id"]').append(
                                        `<option value="${response.data.id}" selected>${response.data.type_name}</option>`
                                        );
                                    $('[name="account_type_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('');
                        });
                }
            } else if ($('#commonModal').find('form').hasClass('tax_register_categories')) {
                if ($('#commonModal').find('form').find('input[name="name"]').val().trim() == '') {
                    $('#commonModal').find('.error_name').show();
                    return;
                } else {
                    let formdata = new FormData($('#commonModal').find('form')[0]);

                    $.ajax({
                            url: "{{ route('tax-register-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="tax_register_category_id"]').append(
                                        `<option value="${response.data.id}" selected>${response.data.name}</option>`
                                        );
                                    $('[name="tax_register_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('');
                        });
                }
            }

            error = 1;
        })
    </script>
@endsection
