@extends('layouts.app')
@section('title', __('clinicCore::lang.clinic_locations'))

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

@section('content')
<section class="content-header">
    <h1><i class="fas fa-map-marker-alt"></i> @lang('clinicCore::lang.clinic_locations')</h1>
</section>

<section class="content">
    @component('components.widget', ['class' => 'box-primary'])
        @slot('tool')
            <div class="box-tools">
                <button class="btn btn-primary btn-sm" id="btn-add-location">
                    <i class="fa fa-plus"></i> @lang('clinicCore::lang.add_new')
                </button>
            </div>
        @endslot

        <table class="table table-bordered table-striped" id="locations_table">
            <thead>
                <tr>
                    <th>@lang('clinicCore::lang.name')</th>
                    <th>ERP Business Location</th>
                    <th>@lang('clinicCore::lang.address')</th>
                    <th>@lang('clinicCore::lang.phone')</th>
                    <th>@lang('clinicCore::lang.status')</th>
                    <th>@lang('clinicCore::lang.actions')</th>
                </tr>
            </thead>
        </table>
    @endcomponent
</section>

{{-- Modal --}}
<div class="modal fade" id="locationModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" style="font-size:15px;"><span>&times;</span></button>
                <h4 class="modal-title" id="locationModalTitle">@lang('clinicCore::lang.add_new')</h4>
            </div>
            <form id="locationForm">
                <div class="modal-body">
                    <input type="hidden" id="location_id">

                    <div class="form-group">
                        <label>@lang('clinicCore::lang.name') <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="location_name" required>
                    </div>

                    {{-- Link to ERP business location --}}
                    <div class="form-group">
                        <label>
                            Link to ERP Business Location <span class="text-danger">*</span>
                            <small class="text-muted">— auto-fills address, phone &amp; email</small>
                        </label>
                        <select id="location_business_location_id" class="form-control select2" style="width:100%">
                            <option value="">— Not linked —</option>
                            @foreach($businessLocations as $bl)
                            <option value="{{ $bl->id }}"
                                data-name="{{ $bl->name }}"
                                data-address="{{ trim(implode(', ', array_filter([$bl->landmark, $bl->city, $bl->state, $bl->country]))) }}"
                                data-phone="{{ $bl->mobile ?? $bl->alternate_number }}"
                                data-email="{{ $bl->email }}">
                                {{ $bl->name }}{{ $bl->city ? ' — ' . $bl->city : '' }}
                            </option>
                            @endforeach
                        </select>
                    </div>
                    <div class="form-group">
                        <label>@lang('clinicCore::lang.address')</label>
                        <textarea class="form-control" id="location_address" rows="2"></textarea>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.phone')</label>
                                <input type="text" class="form-control" id="location_phone">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>@lang('clinicCore::lang.email')</label>
                                <input type="email" class="form-control" id="location_email">
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>@lang('clinicCore::lang.notes')</label>
                        <textarea class="form-control" id="location_notes" rows="2"></textarea>
                    </div>
                    <div class="form-group">
                        <label>@lang('clinicCore::lang.status')</label>
                        <select class="form-control" id="location_status">
                            <option value="active">@lang('clinicCore::lang.active')</option>
                            <option value="inactive">@lang('clinicCore::lang.inactive')</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">@lang('clinicCore::lang.cancel')</button>
                    <button type="submit" class="btn btn-primary">@lang('clinicCore::lang.save')</button>
                </div>
            </form>
        </div>
    </div>
</div>
@endsection

@section('javascript')
<script>
var locTable = $('#locations_table').DataTable({
    processing: true, serverSide: true,
    ajax: '{{ route('clinic.locations.list') }}',
    columns: [
        { data: 'name' },
        { data: 'erp_location', orderable: false },
        { data: 'address', orderable: false },
        { data: 'phone', orderable: false },
        { data: 'status_badge', orderable: false },
        { data: 'action', orderable: false, searchable: false },
    ]
});

// Init select2 inside modal — destroy first to avoid double-init
$('#locationModal').on('shown.bs.modal', function () {
    var $sel = $('#location_business_location_id');
    if ($sel.hasClass('select2-hidden-accessible')) {
        $sel.select2('destroy');
    }
    $sel.select2({
        width: '100%',
        dropdownParent: $('#locationModal'),
        placeholder: '— Not linked —',
        allowClear: true,
    });
});

// Auto-fill address fields when an ERP location is chosen
$(document).on('change', '#location_business_location_id', function () {
    var $opt = $(this).find(':selected');
    if (!$opt.val()) return;
    // Always fill; overwrite only if field is empty
    if (!$('#location_name').val())    $('#location_name').val($opt.data('name'));
    if (!$('#location_address').val()) $('#location_address').val($opt.data('address') || '');
    if (!$('#location_phone').val())   $('#location_phone').val($opt.data('phone') || '');
    if (!$('#location_email').val())   $('#location_email').val($opt.data('email') || '');
});

$('#btn-add-location').on('click', function () {
    $('#locationModalTitle').text('{{ __('clinicCore::lang.add_new') }}');
    $('#location_id').val('');
    $('#locationForm')[0].reset();
    // Select2 needs an explicit trigger to clear visual state
    $('#location_business_location_id').val('').trigger('change');
    $('#locationModal').modal('show');
});

$(document).on('click', '.btn-edit-location', function () {
    var id = $(this).data('id');
    $.get('{{ url('clinic/locations') }}/' + id + '/edit', function (data) {
        $('#locationModalTitle').text('{{ __('clinicCore::lang.edit') }}');
        $('#location_id').val(data.id);
        // null-safe: if business_location_id is null, pass '' so select2 shows "Not linked"
        $('#location_business_location_id').val(data.business_location_id || '').trigger('change');
        $('#location_name').val(data.name || '');
        $('#location_address').val(data.address || '');
        $('#location_phone').val(data.phone || '');
        $('#location_email').val(data.email || '');
        $('#location_notes').val(data.notes || '');
        $('#location_status').val(data.status || 'active');
        $('#locationModal').modal('show');
    }).fail(function () { toastr.error('Failed to load location data.'); });
});

$('#locationForm').on('submit', function (e) {
    e.preventDefault();
    var bizLocId = $('#location_business_location_id').val();
    if (!bizLocId) {
        toastr.error('Please select a linked ERP Business Location.');
        $('#location_business_location_id').next('.select2-container').find('.select2-selection').css('border-color','#e74c3c');
        return;
    }
    $('#location_business_location_id').next('.select2-container').find('.select2-selection').css('border-color','');

    var id  = $('#location_id').val();
    var url = id ? '{{ url('clinic/locations') }}/' + id + '/update' : '{{ route('clinic.locations.store') }}';
    $.post(url, {
        _token:                  '{{ csrf_token() }}',
        business_location_id:    bizLocId,
        name:                    $('#location_name').val(),
        address:                 $('#location_address').val(),
        phone:                   $('#location_phone').val(),
        email:                   $('#location_email').val(),
        notes:                   $('#location_notes').val(),
        status:                  $('#location_status').val(),
    }, function (res) {
        if (res.success) {
            $('#locationModal').modal('hide');
            toastr.success(res.msg);
            locTable.ajax.reload();
        }
    }).fail(function (xhr) {
        var msg = xhr.responseJSON?.errors?.business_location_id?.[0]
               ?? xhr.responseJSON?.message
               ?? 'Save failed.';
        toastr.error(msg);
    });
});

$(document).on('click', '.btn-delete-location', function () {
    var id = $(this).data('id');
    if (!confirm('{{ __('clinicCore::lang.are_you_sure') }}')) return;
    $.ajax({
        url:  '{{ url('clinic/locations') }}/' + id,
        type: 'DELETE',
        data: { _token: '{{ csrf_token() }}' },
        success: function (res) {
            if (res.success) { toastr.success(res.msg); locTable.ajax.reload(); }
            else             { toastr.error(res.msg); }
        },
        error: function (xhr) {
            toastr.error(xhr.responseJSON?.msg ?? 'Cannot delete this location.');
        }
    });
});
</script>
@endsection
