@extends('layouts.app')
@section('title','Add New Company')
@section('pages')

<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> Compwwdany</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 Company</li>
            </ol>
        </nav>
    </div>
    <div class="ms-auto">
        <div class="btn-group">
            <a href="{{route('companies.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('companies.store')}}" method="post" enctype='multipart/form-data' id="company_form">
                        <!-- For validation comment on -->

                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-body g-3 row">
                                    <h5 class="mb-0">Company Basic Information</h5>
                                    <hr class="mb-0">
                                    @csrf
                                    <div class="col-md-12">
                                        <label for="validatinCustom01" class="form-label">Company Name <span class="text-danger"><b>*</b></span></label>
                                        <input type="text" class="form-control" id="validationCustom01" value="{{ old('name') }}" name="name" required>
                                        @if ($errors->has('name'))
                                        <span class="text-danger">{{ $errors->first('name') }}</span>
                                        @endif
                                        <span class="text-danger error_name" style="display:none;">This field is required.</span>
                                    </div>

                                    <div class="col-md-6">
                                        <label for="validationCustom04" class="form-label">Office Type <span class="text-danger"><b>*</b></span></label>
                                        <select class="form-control" id="validationCustom04" name="office_type" required>
                                            <option value="head_office">Head Office</option>
                                            <option value="Branch Office">Branch Office</option>
                                        </select>
                                        @if($errors->has('office_type'))
                                        <span class="text-danger">{{ $errors->first('office_type') }}</span>
                                        @endif
                                    </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',$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-4">
                                        <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-4">
                                        <label class="form-label">City</label>
                                        <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-4">
                                        <label class="form-label">Pin Code/Zip Code</label>
                                        <input type="text" class="form-control" name="pin_code"  value="{{old('pin_code')}}" />
                                    </div>
                                    <div class="col-md-12">
                                        <label class="form-label">Address</label>
                                        <textarea class="form-control" rows="1" name="address_1" >{{old('address_1')}}</textarea>
                                    </div>
                                    <div class="col-md-6 phone_no_col">
                                        <label class="form-label">Phone no<span class="text-danger"><b>*</b></span></label>
                                        <input type="tel" class="form-control" placeholder="" id="phone_number" value="{!! old('phone_number') !!}" />
                                        <input type="hidden" name="phone_number">

                                        @if ($errors->has('phone_number'))
                                        <span class="text-danger">{{ $errors->first('phone_number') }}</span>
                                        @endif
                                        <span class="text-danger error_phone" style="display:none;">This field is required.</span>
                                    </div>

                                    <div class="col-md-6">
                                        <label for="validationCustomUsername" class="form-label">Email </label>
                                        <div class="input-group has-validation"> <span class="input-group-text" id="inputGroupPrepend">@</span>
                                            <input type="email" class="form-control" id="validationCustomUsername" value="{{old('email')}}" name="email" aria-describedby="inputGroupPrepend" required>
                                            @if ($errors->has('email'))
                                            <span class="text-danger">{{ $errors->first('email') }}</span>
                                            @endif
                                        </div>
                                        <span class="text-danger error_email" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Company Establishment Type</label>
                                        <select class="form-control" id="establishment_type_id" name="establishment_type_id">
                                            <option value=" "> Select Type</option>
                                            @foreach($establishment_types as $list)
                                            <option value="{{ $list->id}}" {!! $list->is_default == 1 ? 'selected' : '' !!}>{{$list->name}}</option>
                                            @endforeach
                                        </select>
                                    </div>

                                    <div class="col-md-6">
                                        <label for="tag_line" class="form-label">Company Tag Line</label>
                                        <textarea class="form-textarea" placeholder=""  name="tag_line" rows="1">{{old('tag_line')}}</textarea>
                                    </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 Company 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">Company Address Information</h5>
                                    <hr class="mb-0">
                                    <div class="col-md-6 mobile_no_col">
                                        <label class="form-label">Mobile no </label>
                                        <input type="tel" class="form-control" placeholder="" id="mobile_no" value="{!! old('mobile_number') !!}"/>
                                        <input type="hidden" name="mobile_number">
                                        @if ($errors->has('mobile_number'))
                                        <span class="text-danger">{{ $errors->first('mobile_number') }}</span>
                                        @endif
                                    </div>
                                    <div class="col-md-6 whatsapp_no_col">
                                        <label class="form-label">Whatsapp no </label>
                                        <input type="tel" class="form-control" placeholder="" id="whatsapp_no" value="{!! old('whatsapp_no') !!}"/>
                                        <input type="hidden" name="whatsapp_no">
                                        @if ($errors->has('whatsapp_no'))
                                        <span class="text-danger">{{ $errors->first('whatsapp_no') }}</span>
                                        @endif
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Branch Name</label>
                                        <input type="text" class="form-control" value="{{old('branch_name')}}" placeholder="" name="branch_name" />
                                        @if ($errors->has('branch_name'))
                                        <span class="text-danger">{{ $errors->first('branch_name') }}</span>
                                        @endif
                                        <span class="text-danger error_branch_name" style="display:none;">This field is required.</span>
                                    </div>

                                    <div class="col-md-6">
                                        <label class="form-label">Branch Code</label>
                                        <input type="text" class="form-control" placeholder="" value="{{old('branch_code')}}" name="branch_code" />
                                        @if ($errors->has('branch_code'))
                                        <span class="text-danger">{{ $errors->first('branch_code') }}</span>
                                        @endif
                                        <span class="text-danger error_branch_code" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Website URL</label>
                                        <input type="text" class="form-control" placeholder="" value="{{old('website')}}" name="website" />
                                        @if ($errors->has('website'))
                                        <span class="text-danger">{{ $errors->first('website') }}</span>
                                        @endif
                                        <span class="text-danger error_website" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-6">
                                        <label for="validationCustom04" class="form-label">Letter Head </label>
                                        <select class="form-control" id="" name="letter_head" required>
                                            <option value="head_office">Head Office</option>
                                            <option value="self" selected>Self</option>
                                        </select>
                                        @if($errors->has('letter_head'))
                                        <span class="text-danger">{{ $errors->first('letter_head') }}</span>
                                        @endif
                                    </div>
                                    <div class="col-md-6">
                                        <label for="deals_in" class="form-label">Deal's in </label>
                                        <input type="text" class="form-control" name="deals_in" value="{{old('deals_in')}}" />
                                        @if($errors->has('deals_in'))
                                        <span class="text-danger">{{ $errors->first('deals_in') }}</span>
                                        @endif
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Google Place Link</label>
                                        <input type="text" class="form-control" name="google_place_link" value="{{old('google_place_link')}}" />
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Location Latitude</label>
                                        <input type="text" class="form-control" name="location_latitude" value="{{old('location_latitude')}}" />
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Location Longitude</label>
                                        <input type="text" class="form-control" name="location_longitude" value="{{old('location_longitude')}}" />
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Default Date Format</label>
                                        <select class="form-control" id="date_format" name="date_format">
                                            @foreach($date_format as $key => $list)
                                            <option value="{{ $list->format }}" {!! matchSelected($list->is_default, '1') !!}>{{ $list->format }} ({{ $list->format_details }})</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Default Time Format</label>
                                        <select class="form-control" id="time_format" name="time_format">
                                            @foreach($time_format as $key => $list)
                                             <option value="{{ $list->time_format_name }}" {!! matchSelected($list->is_default, '1') !!}>{{ $list->time_format_name }} ({{ $list->time_format_details }})</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Default Timezone</label>
                                        <select class="form-control" id="time_zone" name="time_zone">
                                            @foreach($time_zone as $key => $list)
                                            <option value="{{ $list->name }}" {!! matchSelected($list->is_default, '1') !!}>{{ $list->details }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Default Language</label>
                                        <select class="form-control" id="language_id" name="language_id">
                                            @foreach($languages as $key => $list)
                                            <option value="{{ $list->id }}">{{ $list->name }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Default Currency</label>
                                        <select class="form-control" id="currency_id" name="currency_id">
                                            @foreach($currencies as $key => $list)
                                            <option value="{{ $list->id }}">{{ $list->currency }} ({{ $list->countries->name ?? ''}})</option>
                                            @endforeach
                                        </select>
                                    </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>

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

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

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

        $('.error_name').hide();

        $('.error_phone').hide();
        $('.error_country_id').hide();
        var error = 0;

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

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

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

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

                          setTimeout(function() {
                            window.location.href = "{!! route('companies.index') !!}"
                          }, 1000);
                      } 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_number, #whatsapp_no, #alternative_no, #mobile_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();
        let cityid  = $('input[name="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);
            }
        });
    })

</script>
<script>
    var loopCount=1;
    function addmore()
    {
        var new_item='<div class="row mt-3" id="rows'+loopCount+'">\
        <div class="col-md-3">\
        <label for="validationTextarea" class="form-label">License Name</label>\
        <select class="form-control" name="license_name[]">\
            <option value=" ">--Select--</option>';
           @foreach($companyLicense as $list)
                new_item+='<option value="{{$list->id}}">{{$list->license_type_name}}</option>';
            @endforeach
            new_item+='</select>\
    </div>\
    <div class="col-md-3">\
        <label for="validationTextarea" class="form-label">License Number</label>\
        <input type="text" class="form-control" placeholder="" name="license_number[]" value="" />\
    </div>\
    <div class="col-md-2">\
        <label for="validationTextarea" class="form-label">Valid From</label>\
        <input type="date" class="form-control" placeholder="" name="valid_from[]" value="" />\
    </div>\
    <div class="col-md-2">\
        <label for="validationTextarea" class="form-label">Valid Upto</label>\
        <input type="date" class="form-control" placeholder="" name="valid_upto[]" value="" />\
    </div>\
    <div class="col-md-2 mt-2">\
            <a onclick="addmore()" class="btn btn-success btn-sm mt-3"><i class="bi bi-plus"></i></a>&nbsp;\
            <a onclick="remove('+loopCount+')" class="btn btn-danger btn-sm mt-3"><i class="bi bi-trash"></i></a>\
    </div>\
    </div>';

    $('#rows').append(new_item);
        loopCount++;
    }

    function remove(ids) {
        $('#rows' + ids).remove();
    }

</script>
@endsection
