@extends('layouts.app')

@section('title', isset($owner) ? __('clinicCore::lang.edit') : __('clinicCore::lang.add_new'))

@section('css')
@include('clinicCore::partials._mobile_responsive')
@endsection

@section('content')
<section class="content-header">
    <h1><i class="fas fa-user-plus"></i>
        {{ isset($owner) ? __('clinicCore::lang.edit') : __('clinicCore::lang.add_new') }}
        — @lang('clinicCore::lang.pet_owner')
    </h1>
</section>

<section class="content">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            @component('components.widget', ['class' => 'box-primary', 'title' => __('clinicCore::lang.patient_contact_details')])

                @if(!isset($owner))
                {{-- Item #1 - explicit two-mode picker.
                     Forces the user to either select an EXISTING ERP
                     customer (Select2 AJAX) OR confirm a NEW customer
                     creation. No third "implicit" path that silently
                     creates customers without the user noticing. --}}
                <div class="form-group">
                    <label style="display:block;margin-bottom:6px;font-weight:700;">
                        Customer record <span class="text-danger">*</span>
                    </label>
                    <div class="btn-group btn-group-justified" data-toggle="buttons" id="clc_customer_mode_group">
                        <label class="btn btn-default active" data-mode="existing">
                            <input type="radio" name="clc_customer_mode" value="existing" checked>
                            <i class="fa fa-search"></i> Select existing customer
                        </label>
                        <label class="btn btn-default" data-mode="new">
                            <input type="radio" name="clc_customer_mode" value="new">
                            <i class="fa fa-user-plus"></i> Create new customer
                        </label>
                    </div>
                </div>

                <div id="clc_existing_customer_block" class="form-group">
                    <label>Search ERP customer (by name / mobile / email)</label>
                    <select id="existing_contact" class="form-control" style="width:100%">
                        <option value=""></option>
                    </select>
                    <small class="text-muted" id="contact_hint">
                        <i class="fa fa-info-circle"></i>
                        Pick the contact this patient refers to. Their name / mobile / email
                        below will auto-fill from the chosen record.
                    </small>
                    <small class="text-info" id="contact_id_display" style="display:none;margin-top:6px;"></small>
                </div>

                <div id="clc_new_customer_block" class="alert alert-info" style="display:none;font-size:12.5px;">
                    <i class="fa fa-user-plus"></i>
                    A <strong>new ERP customer</strong> will be created with the name / mobile / email
                    you fill in below, and immediately linked as this patient owner.
                </div>

                <hr>
                @endif

                <form method="POST" action="{{ isset($owner) ? route('clinic.patient-contacts.update', $owner->id) : route('clinic.patient-contacts.store') }}">
                    @csrf
                    <input type="hidden" name="contact_id" id="hidden_contact_id" value="{{ isset($owner) ? $owner->contact_id : '' }}">

                    @if(isset($owner))
                    <div class="alert alert-info alert-sm" style="padding:6px 12px;margin-bottom:10px;">
                        <i class="fa fa-info-circle"></i>
                        @lang('clinicCore::lang.linked_contact') — Contact ID: <strong>{{ optional($owner->contact)->contact_id }}</strong>
                    </div>
                    @endif

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group {{ $errors->has('name') ? 'has-error' : '' }}">
                                <label>@lang('clinicCore::lang.owner_name') <span class="text-danger">*</span></label>
                                <input type="text" name="name" class="form-control {{ isset($owner) ? 'bg-gray' : '' }}"
                                    value="{{ old('name', isset($owner) ? optional($owner->contact)->name : '') }}"
                                    {{ isset($owner) ? 'readonly' : '' }} required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.mobile')</label>
                                <input type="text" name="mobile" class="form-control {{ isset($owner) ? 'bg-gray' : '' }}"
                                    value="{{ old('mobile', isset($owner) ? optional($owner->contact)->mobile : '') }}"
                                    {{ isset($owner) ? 'readonly' : '' }}>

                                {{-- Item #2 - WA availability at creation time. Stored as
                                     contacts.clc_has_whatsapp (1=yes / 0=no / NULL=unknown).
                                     The Send Message UI uses this to gate the WA option. --}}
                                @php
                                    $waCurrent = isset($owner) ? optional($owner->contact)->clc_has_whatsapp : null;
                                @endphp
                                <div style="margin-top:7px;display:flex;align-items:center;gap:6px;font-size:12px;">
                                    <span style="color:#475569;font-weight:600;display:flex;align-items:center;gap:5px;">
                                        <i class="fab fa-whatsapp" style="color:#16a34a;"></i> WhatsApp:
                                    </span>
                                    <div class="vc-wa-create-group btn-group btn-group-xs" data-toggle="buttons">
                                        @foreach(['yes'=>'Yes','no'=>'No','unknown'=>'Unknown'] as $v => $lbl)
                                            @php
                                                $isOn = ($waCurrent === 1 && $v === 'yes')
                                                     || ($waCurrent === 0 && $v === 'no')
                                                     || ($waCurrent === null && $v === 'unknown');
                                            @endphp
                                            <label class="btn btn-default btn-xs {{ $isOn ? 'active' : '' }} vc-wa-pill"
                                                   data-val="{{ $v }}"
                                                   style="{{ $isOn && $v === 'yes' ? 'background:#16a34a;color:#fff;border-color:#16a34a;' : '' }}{{ $isOn && $v === 'no' ? 'background:#dc2626;color:#fff;border-color:#dc2626;' : '' }}">
                                                <input type="radio" name="clc_has_whatsapp" value="{{ $v }}" {{ $isOn ? 'checked' : '' }}> {{ $lbl }}
                                            </label>
                                        @endforeach
                                    </div>
                                </div>
                                <small class="text-muted" style="font-size:11px;">
                                    Used to gate WhatsApp reminders + the per-owner messaging menu.
                                </small>
                            </div>
                        </div>
                    </div>
                    <script>
                    // Bootstrap's btn-group-toggle data-api re-renders state when a
                    // radio is clicked; we also re-apply our colour overrides here
                    // because the active style is set inline (not in a stylesheet).
                    $(function () {
                        $(document).on('click', '.vc-wa-create-group .vc-wa-pill', function () {
                            $('.vc-wa-create-group .vc-wa-pill').css({background:'',color:'',borderColor:''});
                            var v = $(this).data('val');
                            if (v === 'yes') $(this).css({background:'#16a34a',color:'#fff',borderColor:'#16a34a'});
                            if (v === 'no')  $(this).css({background:'#dc2626',color:'#fff',borderColor:'#dc2626'});
                        });
                    });
                    </script>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.email')</label>
                                <input type="email" name="email" class="form-control {{ isset($owner) ? 'bg-gray' : '' }}"
                                    value="{{ old('email', isset($owner) ? optional($owner->contact)->email : '') }}"
                                    {{ isset($owner) ? 'readonly' : '' }}>

                                @if(isset($owner) && optional($owner->contact)->email)
                                    <div style="margin-top:7px;display:flex;align-items:center;gap:8px;flex-wrap:wrap;">
                                        @if($owner->email_confirmed)
                                            <span class="label label-success" style="font-size:12px;padding:4px 10px;">
                                                <i class="fa fa-check-circle"></i> Email Confirmed
                                            </span>
                                        @elseif($owner->email_confirm_sent_at)
                                            <span class="label label-warning" style="font-size:12px;padding:4px 10px;">
                                                <i class="fa fa-clock"></i> Confirmation Sent
                                            </span>
                                            <button type="button" class="btn btn-xs btn-default btn-resend-confirm"
                                                    data-id="{{ $owner->id }}" data-url="{{ route('clinic.patient-contacts.resend-confirmation', $owner->id) }}">
                                                <i class="fa fa-refresh"></i> Resend
                                            </button>
                                        @else
                                            <span class="label label-default" style="font-size:12px;padding:4px 10px;">
                                                <i class="fa fa-envelope"></i> Not Sent
                                            </span>
                                            <button type="button" class="btn btn-xs btn-primary btn-resend-confirm"
                                                    data-id="{{ $owner->id }}" data-url="{{ route('clinic.patient-contacts.resend-confirmation', $owner->id) }}">
                                                <i class="fa fa-envelope"></i> Send Confirmation
                                            </button>
                                        @endif
                                        <small class="text-muted" id="resend_result_{{ $owner->id }}"></small>
                                    </div>
                                @elseif(!isset($owner))
                                    <small class="text-info" style="display:block;margin-top:5px;">
                                        <i class="fa fa-info-circle"></i> A confirmation email will be sent automatically if an email is entered.
                                    </small>
                                @endif
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.occupation')</label>
                                <input type="text" name="occupation" class="form-control"
                                    value="{{ old('occupation', isset($owner) ? $owner->occupation : '') }}">
                            </div>
                        </div>
                    </div>

                    <h4>@lang('clinicCore::lang.emergency_contact')</h4>
                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.emergency_contact_name')</label>
                                <input type="text" name="emergency_contact_name" class="form-control"
                                    value="{{ old('emergency_contact_name', isset($owner) ? $owner->emergency_contact_name : '') }}">
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.emergency_contact_phone')</label>
                                <input type="text" name="emergency_contact_phone" class="form-control"
                                    value="{{ old('emergency_contact_phone', isset($owner) ? $owner->emergency_contact_phone : '') }}">
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.emergency_contact_relation')</label>
                                <input type="text" name="emergency_contact_relation" class="form-control"
                                    value="{{ old('emergency_contact_relation', isset($owner) ? $owner->emergency_contact_relation : '') }}">
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.referred_by')</label>
                                <input type="text" name="referred_by" class="form-control"
                                    value="{{ old('referred_by', isset($owner) ? $owner->referred_by : '') }}">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label><i class="fa fa-user-md text-primary"></i> @lang('clinicCore::lang.preferred_doctor')</label>
                                <select name="preferred_doctor_id" id="preferred_doctor_id" class="form-control">
                                    <option value="">— @lang('clinicCore::lang.no_preferred_doctor') —</option>
                                    @foreach(($doctors ?? []) as $doc)
                                        <option value="{{ $doc->id }}"
                                            {{ (string) old('preferred_doctor_id', isset($owner) ? $owner->preferred_doctor_id : '') === (string) $doc->id ? 'selected' : '' }}>
                                            {{ $doc->name }}{{ $doc->specialization ? ' — ' . $doc->specialization : '' }}
                                        </option>
                                    @endforeach
                                </select>
                                <small class="text-muted">@lang('clinicCore::lang.preferred_doctor_hint')</small>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>@lang('clinicCore::lang.notes')</label>
                        <textarea name="notes" class="form-control" rows="2">{{ old('notes', isset($owner) ? $owner->notes : '') }}</textarea>
                    </div>

                    <div class="form-group">
                        <button type="submit" class="btn btn-primary">
                            <i class="fa fa-save"></i> {{ isset($owner) ? __('clinicCore::lang.update') : __('clinicCore::lang.save') }}
                        </button>
                        <a href="{{ route('clinic.patient-contacts.index') }}" class="btn btn-default">@lang('clinicCore::lang.cancel')</a>
                    </div>
                </form>
            @endcomponent
        </div>
    </div>
</section>
@endsection

@section('javascript')
<script>
$(document).ready(function() {
    $('#preferred_doctor_id').select2({ width: '100%', placeholder: '— Select preferred doctor —', allowClear: true });

    $('#existing_contact').select2({
        width: '100%',
        minimumInputLength: 1,
        minimumResultsForSearch: -1,
        ajax: {
            url: '{{ route('clinic.patient-contacts.search') }}',
            dataType: 'json',
            delay: 300,
            data: function (params) { return { q: params.term }; },
            processResults: function (data) { return { results: data }; },
            error: function(xhr) {
                console.error('Search error:', xhr.status, xhr.responseText);
            }
        },
        placeholder: 'Search by name / phone / email',
        allowClear: true,
        language: {
            inputTooShort: function() { return 'Type to search...'; },
            noResults: function() { return 'No customers found'; },
            searching: function() { return 'Searching...'; }
        }
    });

    $('#existing_contact').on('select2:select', function (e) {
        var d = e.params.data;
        $('#hidden_contact_id').val(d.id);
        $('input[name="name"]').val(d.name || '').prop('readonly', true).addClass('bg-gray');
        $('input[name="mobile"]').val(d.mobile || '').prop('readonly', true).addClass('bg-gray');
        $('input[name="email"]').val(d.email || '').prop('readonly', true).addClass('bg-gray');
        $('#contact_hint').hide();
        $('#contact_id_display').text('Contact ID: ' + d.id).show();
    });

    $('#existing_contact').on('select2:unselect select2:clear', function () {
        $('#hidden_contact_id').val('');
        $('input[name="name"]').val('').prop('readonly', false).removeClass('bg-gray');
        $('input[name="mobile"]').val('').prop('readonly', false).removeClass('bg-gray');
        $('input[name="email"]').val('').prop('readonly', false).removeClass('bg-gray');
        $('#contact_hint').show();
        $('#contact_id_display').hide();
    });

    // Item #1 - explicit two-mode picker. Switching to "new" clears any
    // selected existing-contact AND unlocks the name/mobile/email fields
    // so the doctor explicitly types the new customer details.
    $('#clc_customer_mode_group .btn').on('click', function () {
        var mode = $(this).data('mode');
        $('#clc_customer_mode_group .btn').removeClass('active');
        $(this).addClass('active');
        if (mode === 'existing') {
            $('#clc_existing_customer_block').show();
            $('#clc_new_customer_block').hide();
        } else {
            $('#clc_existing_customer_block').hide();
            $('#clc_new_customer_block').show();
            // Clear any prior existing-contact selection so the form
            // submits as a brand-new customer creation.
            $('#existing_contact').val(null).trigger('change');
            $('#hidden_contact_id').val('');
            $('input[name="name"]').val('').prop('readonly', false).removeClass('bg-gray').focus();
            $('input[name="mobile"]').val('').prop('readonly', false).removeClass('bg-gray');
            $('input[name="email"]').val('').prop('readonly', false).removeClass('bg-gray');
        }
    });

    // Item #1 - require an explicit choice before submission.
    // In "existing" mode: a contact MUST be selected.
    // In "new" mode: name is required (mobile / email validated server-side).
    $('form').on('submit', function (e) {
        var mode = $('input[name="clc_customer_mode"]:checked').val() || 'existing';
        if (mode === 'existing' && !$('#hidden_contact_id').val()) {
            e.preventDefault();
            toastr.warning('Please select an existing customer from the search box, or switch to "Create new customer" mode.');
            $('#existing_contact').select2('open');
            return false;
        }
    });

    $(document).on('click', '.btn-resend-confirm', function () {
        var $btn = $(this);
        var url  = $btn.data('url');
        var id   = $btn.data('id');
        $btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i>');
        $.ajax({
            url:    url,
            method: 'POST',
            data:   { _token: '{{ csrf_token() }}' },
            success: function (res) {
                if (res.success) {
                    toastr.success(res.msg);
                    $btn.closest('div').find('.label').replaceWith(
                        '<span class="label label-warning" style="font-size:12px;padding:4px 10px;"><i class="fa fa-clock"></i> Confirmation Sent</span>'
                    );
                    $btn.html('<i class="fa fa-refresh"></i> Resend').prop('disabled', false);
                } else {
                    toastr.error(res.msg);
                    $btn.html('<i class="fa fa-refresh"></i> Resend').prop('disabled', false);
                }
            },
            error: function () {
                toastr.error('Failed to send confirmation email.');
                $btn.html('<i class="fa fa-refresh"></i> Resend').prop('disabled', false);
            }
        });
    });
});
</script>
@endsection
