<style type="text/css">
    .account_title {
        width: 50px;
        border: 1px solid #ced4da;
        border-top-left-radius: 4px;
        border-bottom-left-radius: 4px;
    }
</style>
<form class="row g-3 auto-width update_patient" id="update_patient_form" enctype='multipart/form-data' action="{!! route('patient-account-update', $patient->id) !!}">
    <!-- For validation comment on -->
    <!-- <form class="row g-3 was-validated"> -->
    @csrf
    <div class="col-md-12" style="text-align: right;">
        <label for="name" class="form-label">Show ABHA No./UHID <span class="text-danger"><b>*</b></span></label>
        <input class="form-check-inputFeatured btn-lg abha-toggle" type="checkbox" value="0">
    </div>
    <div class="col-md-12 mt-0">
        <div>
            <label for="name" class="form-label">Patient Full Name <span class="text-danger"><b>*</b></span></label>
        </div>
        <div class="input-group">
            <select class="account_title" name="account_title_id" style="width:120px;">
                <option value="">-Title-</option>
                @foreach($account_title as $list)
                <option value="{{ $list->id }}" {!! matchSelected($patient->account_title_id, $list->id) !!}>{{ $list->name }} - {{ $list->gender->name ?? '' }}</option>
                @endforeach
            </select>
            <input type="text" name="name" class="form-control"  value="{!! $patient->name !!}" placeholder="Full Name">
        </div>
        <span class="text-danger error_name" style="display:none;">This field is required.</span>
    </div>
    <div class="col-md-12 abha-div" style="display:none;">
        <div>
            <label for="account_type_id" class="form-label">ABHA No./UHID<span class="text-danger"><b></b></span></label>
        </div>
        <div class="input-group">
          <input type="text" class="form-control" name="unique_register_no" placeholder="Ayushman Bharat Health Account">
            <div class="input-group-append" style="margin: auto 10px;">
                <button class="btn btn-success" type="button"> <i class="bi bi-arrow-repeat"></i> Get</button>
            </div>
        </div>
        <span class="text-danger error_unique_register_no" style="display:none;">This field is required.</span>
    </div>
    <div class="col-md-12 row mt-3">
        <div class="col-3">
            {{-- <div class="col-12"> --}}
                <label for="date_of_birth" class="form-label"> Age/Years(DOB)<span class="text-danger"><b>*</b></span></label>
            {{-- </div> --}}
            {{-- <label for="date_of_birth" class="form-label">Years</label> --}}
            @php    
                $birthYear = '';
                $birthMonth = '';
                $birthDay = ''; 
            @endphp
                @if(isset($patient->account_contact->date_of_birth))
                @php
                    $birthYear = date('Y',strtotime($patient->account_contact->date_of_birth));
                    $birthMonth = date('m',strtotime($patient->account_contact->date_of_birth));
                    $birthDay = date('d',strtotime($patient->account_contact->date_of_birth));
                @endphp
                @endif
               
            <select id="age_years" name="year" class="form-control">
                <option value="">-Select Year-</option>
                @php
                $currentYear = date('Y');
                @endphp
                @for($year = 0; $year <= 100; $year++)
                    <option value="{!! $currentYear - $year !!}" {!! $birthYear==($currentYear - $year)?'selected':'' !!}>{!! $year !!} -  {!! $currentYear - $year !!}</option>
                @endfor
            </select>

        </div>
        <div class="col-3">
            <label for="date_of_birth" class="form-label">Months(MM)</label>
            <select id="age_months" name="month" class="form-control">
                @foreach(months() as $key => $value)
                    <option value="{!! $key !!}" {!! $birthMonth==$key?'selected':'' !!}>{!! $value  !!}</option>
                @endforeach
            </select>
        </div>
        <div class="col-3">
            <label for="date_of_birth" class="form-label">Days(DD)</label>
            <select id="age_days" name="day" class="form-control" >
                @for($day = 1; $day <= 31; $day++)
                    <option value="{!! $day !!}" {!! $birthDay==$day?'selected':'' !!}>{!! $day !!}</option>
                @endfor
            </select>
        </div>
        <div class="col-3">
            <label for="date_of_birth" class="form-label">Hours(HH)</label>
            <select id="age_hours" name="hour" class="form-control" >
                @for($hour = 0; $hour <= 24; $hour++)
                    <option value="{!! $hour !!}">{!! $hour !!}</option>
                @endfor
            </select>
        </div>
        <span class="text-danger error_date_of_birth" style="display:none;">The date of birth or age are required.</span>
    </div>
    <div class="col-md-6 phone_no_col">
        <div>
            <label class="form-label">Phone no <span class="text-danger"><b>*</b></span></label>
        </div>
        <div class="input-group">
            <input type="tel" class="form-control w-100" placeholder="" id="phone_no"  value="{!! @$patient->account_contact->phone_no !!}"/>
            <input type="hidden" name="phone_no" value="{!! @$patient->account_contact->phone_no !!}">
        </div>
        <span class="text-danger error_phone" style="display:none;">This field is required.</span>
    </div>
    <div class="col-md-6 phone_no_col" style="display: none">
        <div>
            <label class="form-label">Date of Birth <span class="text-danger"><b>*</b></span></label>
        </div>
        <div class="input-group">
            <input type="datetime-local" class="form-control w-100"  placeholder="" name="date_of_birth" value="" readonly />
        </div>
        <span class="text-danger error_date_of_birth" style="display:none;">This field is required.</span>
    </div>

    <div class="col-md-6 whatsapp_no_col">
        <div>
            <label class="form-label">Whatsapp no </label>
        </div>
        <div class="input-group">
            <input type="tel" class="form-control" placeholder="" id="whatsapp_no"  value="{!! @$patient->account_contact->whatsapp_no !!}"/>
            <input type="hidden" name="whatsapp_no" value="{!! @$patient->account_contact->whatsapp_no !!}">
        </div>
    </div>
    <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- </option>
            @foreach($bloodGroup as $list)
            <option value="{{ $list->id}}" {!! matchSelected(($patient->account_contact->blood_group_id ?? ''), $list->id) !!}>{{$list->group}}</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- </option>
            @foreach($maritalStatus as $list)
            <option value="{{ $list->id}}" {!! matchSelected(($patient->account_contact->marital_status ?? ''), $list->id) !!}>{{$list->name}}</option>
            @endforeach
        </select>
        <span class="text-danger marital_status_id" style="display:none;">This field is required.</span>
    </div>

    <div class="col-md-6">
        <div>
            <label class="form-label">Email </label>
        </div>
        <div class="input-group">
            <input type="text" class="form-control" placeholder="Email" value="{!! @$patient->account_contact->email !!}" name="email" />
        </div>
    </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}}" {!! matchSelected(@$patient->account_contact['country_id'], $list->id) !!}>{{$list->name}}</option>
            @endforeach
        </select>
    </div>

    <div class="col-md-6">
        <label class="form-label">State</label>
        <input type="hidden" value="{!! $patient->account_contact->state_id !!}" 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>
        <input type="hidden" value="{!! $patient->account_contact['city_id'] !!}" 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-8">
        <label class="form-label">Address </label>
        <textarea name="address" class="form-control" > {!! $patient->account_contact->address !!} </textarea>
    </div>
    <div class="col-md-4">
        <div>
            <label class="form-label">PIN/Postal code </label>
        </div>
        <div class="input-group">
            <input type="text" class="form-control" placeholder="PIN/Postal code" name="postal_code" value="{!! $patient->account_contact->postal_code !!}">
        </div>
    </div>
    @if($redirect_back == 'ipd_admission')
    <div class="col-md-12">
        <label for="relation_name" class="form-label">Next Of Kin (Relatives Name) <span class="text-danger"><b>*</b></span></label>
        <input type="text" name="relation_name" class="form-control" value="{!! $patient->account_relative->relation_name??'' !!}">
        <span class="text-danger error_relation_name" style="display:none;">This field is required.</span>
    </div>
    <div class="col-md-6">
        <label class="form-label">Relation Type <span class="text-danger"><b>*</b></span></label>
        <select class="single-select form-control" id="relation_type" name="relation_type" required>
            <option value="">Select Relation Ship</option>
            @foreach($types as $type)
            <option value="{!! $type->relation_name !!}" {!! isset($patient->account_relative->relation_type) && $patient->account_relative->relation_type==$type->relation_name ? 'selected':'' !!}>{!! $type->relation_name !!}</option>
            @endforeach
        </select>
        <span class="text-danger error_address_type_id" style="display: none;">This field is required.</span>
    </div>
    <div class="col-md-6 relation_phone_col">
        <label class="form-label">Relation Phone no<span class="text-danger"><b>*</b></span></label>
        <input type="tel" class="form-control" placeholder="" id="relation_phone" value="{!! $patient->account_relative->relation_phone??'' !!}" />
        <input type="hidden" name="relation_phone" value="{!! $patient->account_relative->relation_phone??'' !!}">

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

<script>

    $('.details-toggle').hide();
    var toggle = 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;
    }
    $("[name='year']").on('input', function() {
        var onlyNumbers = allNumeric($(this).val());

        if (onlyNumbers.length > 4) {
            onlyNumbers = onlyNumbers.substring(0, 4);
        }

        $("[name='year']").val(onlyNumbers);
    });

    $("[name='month']").on('input', function() {
        var month = allNumeric($(this).val());

        if (month > 12) {
            month = 12;
        }

        $("[name='month']").val(month);
    });

    $("[name='day']").on('input', function() {
        var day = parseInt($(this).val());
        if (isNaN(day) || day < 0) {
            day = 0;
        }

        if (day > 31) {
            day = 31;
        }

        $("[name='day']").val(day);
    });
    $("[name='hour']").on('input', function() {
        var day = parseInt($(this).val());
        if (isNaN(day) || day < 0) {
            day = 0;
        }

        if (day > 24) {
            day = 24;
        }

        $("[name='hour']").val(day);
    });
    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,#relation_phone');

                // 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($state_id) ? $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('change', '.abha-toggle', function () {

        if ($(this).prop('checked')==true) {
            $('.abha-div').show();
        } else {
            $('.abha-div').hide();
        }
    })
    $(document).ready(function(){
        $.switcher('.abha-toggle');

        function updateDateOfBirth() {
            var Hours  = $("#age_hours").val() || 0;
            var Days   = $("#age_days").val() || 0;
            var Months = $("#age_months").val() || 0;
            var Years  = $("#age_years").val() || 0;
            Days       = parseInt(Days);
            Months     = parseInt(Months) - 1;

            var dateOfBirth = new Date(Date.UTC(Years, Months, Days,  Hours, 0, 0, 0));


            // Update the date of birth input value
            var formattedDateOfBirth = dateOfBirth.toISOString().slice(0, 16);
            $("input[name='date_of_birth']").val(formattedDateOfBirth);
        }

        function updateAgeFromDOB() {
            var dobString = $("input[name='date_of_birth']").val();
            if(dobString){
                var dob = new Date(dobString);
                var currentDate = new Date();

                // Calculate age
                var ageMilliseconds = currentDate - dob;
                var ageSeconds = ageMilliseconds / 1000;
                var ageMinutes = ageSeconds / 60;
                var ageHours = ageMinutes / 60;
                var ageDays = ageHours / 24;
                var ageMonths = (currentDate.getMonth() - dob.getMonth()) + 12 * (currentDate.getFullYear() - dob.getFullYear());
                var ageYears = currentDate.getFullYear() - dob.getFullYear();

                // Update age inputs
                $("#age_hours").val(Math.round(ageHours));
                $("#age_days").val(Math.round(ageDays));
                $("#age_months").val(ageMonths);
                $("#age_years").val(ageYears);
            }
        }
        $("#age_hours, #age_days, #age_months, #age_years").on('input', function() {
            updateDateOfBirth();
        });

        // Listen for changes in the date of birth input
        $("input[name='date_of_birth']").on('input', function() {
            updateAgeFromDOB();
        });

        // Initialize age calculation based on default date of birth
        updateAgeFromDOB();
    })
</script>

@if($country_id)
    <script>
        changecontry();

        $('#states').trigger('change');
    </script>
  <script>

</script>
@endif
