@extends('layouts.app')
@section('title','Contacts')
@section('pages')
<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 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> Contacts</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 Contact</li>
            </ol>
        </nav>
    </div>
    <div class="ms-auto">
        <div class="btn-group">
            <a href="{{route('contacts.index')}}" class="btn btn-outline-secondary"><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 create_client" action="{{ route('contacts.store')}}" method="post" enctype='multipart/form-data'>
                        <!-- 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">Contact Information</h5>
                                    <hr class="mb-0">
                                    <div class="col-md-6">
                                        <label for="validationCustomUsername" class="form-label">Name <span class="text-danger"><b>*</b></span></label>
                                        <input type="text" class="form-control" id="validationCustomUsername" name="name" value="{{ old('name') }}" aria-describedby="inputGroupPrepend" 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 class="form-label">Organization </label>
                                        <input type="text" class="form-control" placeholder="" name="organization" id="organization" />
                                        @if ($errors->has('organization'))
                                        <span class="text-danger">{{ $errors->first('organization') }}</span>
                                        @endif
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Guardian name</label>
                                        <input type="text" class="form-control" placeholder="" name="guardian_name" />
                                        @if ($errors->has('guardian_name'))
                                        <span class="text-danger">{{ $errors->first('guardian_name') }}</span>
                                        @endif
                                        <span class="text-danger error_guardian_name" 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' : '' !!}>{{$list->name}}</option>
                                            @endforeach
                                        </select>
                                    </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_no" />
                                        <input type="hidden" name="phone_no">

                                        @if ($errors->has('phone_no'))
                                        <span class="text-danger">{{ $errors->first('phone_no') }}</span>
                                        @endif
                                        <span class="text-danger error_phone" style="display:none;">This field is required.</span>
                                    </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" />
                                        <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 alternative_no_col">
                                        <label class="form-label">Alternative no</label>
                                        <input type="tel" class="form-control" placeholder="" id="alternative_no" />
                                        <input type="hidden" name="alternative_no">
                                        @if ($errors->has('alternative_no'))
                                        <span class="text-danger">{{ $errors->first('alternative_no') }}</span>
                                        @endif
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Email</label>
                                        <input type="text" class="form-control" placeholder="" name="email" />
                                        @if ($errors->has('email'))
                                        <span class="text-danger">{{ $errors->first('email') }}</span>
                                        @endif
                                        <span class="text-danger error_email" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Gender</label>
                                        <select class=" form-control" id="account_gender_id" name="account_gender_id">
                                            <option value=""> Select Gender</option>
                                            @foreach($genders as $list)
                                            <option value="{{ $list->id}}">{{$list->name}}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Marital Status</label>
                                        <select class=" form-control" id="marital_status" name="marital_status">
                                            <option value=" "> Select Marital Status</option>
                                            @foreach($maritalStatus as $list)
                                            <option value="{{ $list->id}}">{{$list->name}}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <hr class="mb-0">
                                    <div class="col-12" align="center">
                                        <div class="d-grid gap-2 with-50">
                                          <button class="btn btn-primary save_button" type="button"><i class="bx bx-save"></i> Save Contact</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 Details</h5>
                                    <hr class="mb-0">
                                    <div class="col-md-6">
                                        <label class="form-label">Blood Group</label>
                                        <select class=" form-control" id="blood_group_id" name="blood_group_id">
                                            <option value=" "> Select Blood Group</option>
                                            @foreach($bloodGroup as $list)
                                            <option value="{{ $list->id}}">{{$list->group}}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Anniversary date</label>
                                        <input type="text" class="form-control"  id="date" name="anniversary_date" />
                                        @if ($errors->has('anniversary_date'))
                                        <span class="text-danger">{{ $errors->first('anniversary_date') }}</span>
                                        @endif
                                        <span class="text-danger error_anniversary_date" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Organization type</label>
                                        <select class="form-control" name="organization_type" id="organization_type">
                                        <option value=" ">--Select--</option>
                                            @foreach($organization_types as $list)
                                                <option value="{{ $list->id}}">{{$list->name}}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Website URL </label>
                                        <input type="text" class="form-control" placeholder="" name="website_url" id="website_url" />
                                        @if ($errors->has('website_url'))
                                        <span class="text-danger">{{ $errors->first('website_url') }}</span>
                                        @endif
                                    </div>
                                    <div class="col-md-12">
                                        <label class="form-label">Address </label>
                                        <textarea name="address" class="form-textarea"></textarea>
                                        @if ($errors->has('address'))
                                        <span class="text-danger">{{ $errors->first('address') }}</span>
                                        @endif
                                    </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">
                                        <option value=" ">--Select--</option>
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <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">
                                        <option value=" ">--Select--</option>
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Postal code</label>
                                        <input type="text" class="form-control" placeholder="" name="postal_code" />
                                        @if ($errors->has('postal_code'))
                                        <span class="text-danger">{{ $errors->first('postal_code') }}</span>
                                        @endif
                                        <span class="text-danger error_postal_code" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Pin</label>
                                        <input type="text" class="form-control" placeholder="" name="pin" />
                                        @if ($errors->has('pin'))
                                        <span class="text-danger">{{ $errors->first('pin') }}</span>
                                        @endif
                                        <span class="text-danger error_pin" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-12">
                                        <label class="form-label">Any known allergies</label>
                                        <textarea name="any_known_allergies" class="form-textarea"></textarea>
                                        @if ($errors->has('any_known_allergies'))
                                        <span class="text-danger">{{ $errors->first('any_known_allergies') }}</span>
                                        @endif
                                        <span class="text-danger error_any_known_allergies" style="display:none;">This field is required.</span>
                                    </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://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.10/js/intlTelInput.js"></script>
<script>
    $(document).ready(function(){
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': jQuery('meta[name="csrf-token"]').attr('content')
            }
        });
        changecontry();
        $('#states').trigger('change');

    });
     $( function() {
        $('#date').datepicker();
    });
    $(document).on('click','.save_button', function(e) {
        e.preventDefault();

        if ($('#phone_no').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 ($('#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());
        }

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

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

        if ($('input[name="name"]').val().trim() == '') {
          $('.error_name').show();
          error = 1;
        }
        if ($('input[name="phone_no"]').val().trim() == '') {
          $('.error_phone').show();
          error = 1;
        }

        if (error == 0) {
          $('.create_client').submit();
        }
        error = 1;
    })

    var telInput = $('#phone_no , #whatsapp_no , #alternative_no');
    telInput.intlTelInput({
        utilsScript: 'https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.13/js/utils.js', // Update the URL to the correct one
        initialCountry: '{!! $countryCode  !!}', // Set the new country code
        separateDialCode: true
    });

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

    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);
            }
        });
    })
</script>
@endsection
