@extends('clientarea.profile.layout')

@section('profile-content')
    @php
        // Get locked fields from admin settings (PRC-637: tek-kaynak decode)
        $lockedFields = setting_array('locked_client_user_profile_fields', ['email', 'company']);

        // Field mapping for checking
        $fieldMapping = [
            'firstname' => 'first_name',
            'lastname' => 'last_name',
            'email' => 'email',
            'company' => 'company',
            'phone' => 'phone',
            'address1' => 'address1',
            'address2' => 'address2',
            'city' => 'city',
            'state' => 'state',
            'postcode' => 'postcode',
            'country' => 'country_id',
        ];

        // Helper function to check if field is locked
        $isFieldLocked = function($fieldKey) use ($lockedFields, $fieldMapping) {
            $formField = $fieldMapping[$fieldKey] ?? $fieldKey;
            return in_array($fieldKey, $lockedFields);
        };
    @endphp
    @if (session('success'))
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        {{ session('success') }}
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
    @endif

    @if (session('error'))
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        {{ session('error') }}
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
    @endif

    @if ($errors->any())
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <ul class="mb-0">
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
    @endif

<div class="card">
    <div class="card-header">
        <h5 class="mb-0">{{ __('store.clientarea_profile_edit_profile') }}</h5>
    </div>
    <div class="card-body">
        <form method="POST" action="{{ route('store.auth.profile.update') }}" id="profileForm">
            @csrf

            <!-- Personal Information -->
            <h6 class="border-bottom pb-2 mb-3">{{ __('store.auth_personal_information') }}</h6>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label for="first_name" class="form-label">
                        {{ __('store.auth_first_name') }} <span class="text-danger">*</span>
                        @if($isFieldLocked('firstname'))
                            <i class="fas fa-question-circle text-muted ms-1"
                               data-bs-toggle="tooltip"
                               data-bs-placement="top"
                               title="{{ __('store.auth_locked_field_tooltip') }}"></i>
                        @endif
                    </label>
                    <input type="text" class="form-control @error('first_name') is-invalid @enderror"
                           id="first_name" name="first_name" value="{{ old('first_name', $client->first_name) }}"
                           {{ $isFieldLocked('firstname') ? 'readonly' : 'required' }}>
                    @error('first_name')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>

                <div class="col-md-6 mb-3">
                    <label for="last_name" class="form-label">
                        {{ __('store.auth_last_name') }} <span class="text-danger">*</span>
                        @if($isFieldLocked('lastname'))
                            <i class="fas fa-question-circle text-muted ms-1"
                               data-bs-toggle="tooltip"
                               data-bs-placement="top"
                               title="{{ __('store.auth_locked_field_tooltip') }}"></i>
                        @endif
                    </label>
                    <input type="text" class="form-control @error('last_name') is-invalid @enderror"
                           id="last_name" name="last_name" value="{{ old('last_name', $client->last_name) }}"
                           {{ $isFieldLocked('lastname') ? 'readonly' : 'required' }}>
                    @error('last_name')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>

                <div class="col-md-6 mb-3">
                    <label for="email" class="form-label">
                        {{ __('store.auth_email') }} <span class="text-danger">*</span>
                        @if($isFieldLocked('email'))
                            <i class="fas fa-question-circle text-muted ms-1"
                               data-bs-toggle="tooltip"
                               data-bs-placement="top"
                               title="{{ __('store.auth_locked_field_tooltip') }}"></i>
                        @endif
                    </label>
                    <input type="email" class="form-control @error('email') is-invalid @enderror"
                           id="email" name="email" value="{{ old('email', $client->email) }}"
                           {{ $isFieldLocked('email') ? 'readonly' : 'required' }}>
                    @error('email')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>

                <div class="col-md-6 mb-3">
                    <label for="phone" class="form-label">
                        {{ __('store.auth_phone') }}
                        @if($isFieldLocked('phone'))
                            <i class="fas fa-question-circle text-muted ms-1"
                               data-bs-toggle="tooltip"
                               data-bs-placement="top"
                               title="{{ __('store.auth_locked_field_tooltip') }}"></i>
                        @endif
                    </label>
                    <input type="text" class="form-control @error('phone') is-invalid @enderror"
                           id="phone" name="phone" value="{{ old('phone', $client->phone) }}"
                           {{ $isFieldLocked('phone') ? 'readonly' : '' }}>
                    @error('phone')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>

                <div class="col-md-12 mb-3">
                    <label for="company" class="form-label">
                        {{ __('store.auth_company') }}
                        @if($isFieldLocked('company'))
                            <i class="fas fa-question-circle text-muted ms-1"
                               data-bs-toggle="tooltip"
                               data-bs-placement="top"
                               title="{{ __('store.auth_locked_field_tooltip') }}"></i>
                        @endif
                    </label>
                    <input type="text" class="form-control @error('company') is-invalid @enderror"
                           id="company" name="company" value="{{ old('company', $client->company) }}"
                           {{ $isFieldLocked('company') ? 'readonly' : '' }}>
                    @error('company')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
            </div>

            <!-- Address Information -->
            <h6 class="border-bottom pb-2 mb-3 mt-4">{{ __('store.auth_address_information') }}</h6>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label for="country_id" class="form-label">{{ __('store.auth_country') }} <span class="text-danger">*</span></label>
                    <select class="form-select @error('country_id') is-invalid @enderror"
                            id="country_id" name="country_id" required>
                        <option value="">{{ __('store.auth_select_country') }}</option>
                        @foreach($countries as $country)
                            <option value="{{ $country->id }}"
                                    {{ old('country_id', $client->country_id) == $country->id ? 'selected' : '' }}>
                                {{ $country->common_name }}
                            </option>
                        @endforeach
                    </select>
                    @error('country_id')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>

                <div class="col-md-6 mb-3">
                    <label for="city_id" class="form-label">{{ __('store.auth_city') }}</label>
                    <select class="form-select @error('city_id') is-invalid @enderror"
                            id="city_id" name="city_id">
                        <option value="">{{ __('store.auth_select_city') }}</option>
                        @if($client->city_id && $cities)
                            @foreach($cities as $city)
                                <option value="{{ $city->id }}"
                                        {{ old('city_id', $client->city_id) == $city->id ? 'selected' : '' }}>
                                    {{ $city->name }}
                                </option>
                            @endforeach
                        @endif
                    </select>
                    @error('city_id')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>

                <div class="col-md-12 mb-3">
                    <label for="address1" class="form-label">{{ __('store.auth_address1') }}</label>
                    <input type="text" class="form-control @error('address1') is-invalid @enderror"
                           id="address1" name="address1" value="{{ old('address1', $client->address1) }}">
                    @error('address1')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>

                <div class="col-md-6 mb-3">
                    <label for="state" class="form-label">{{ __('store.auth_state') }}</label>
                    <input type="text" class="form-control @error('state') is-invalid @enderror"
                           id="state" name="state" value="{{ old('state', $client->state) }}">
                    @error('state')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>

                <div class="col-md-6 mb-3">
                    <label for="postcode" class="form-label">{{ __('store.auth_postcode') }}</label>
                    <input type="text" class="form-control @error('postcode') is-invalid @enderror"
                           id="postcode" name="postcode" value="{{ old('postcode', $client->postcode) }}">
                    @error('postcode')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
            </div>

            <!-- Custom Fields -->
            @if($customFields && $customFields->count() > 0)
                <h6 class="border-bottom pb-2 mb-3 mt-4">{{ __('store.auth_additional_information') }}</h6>
                <div class="row">
                    @foreach($customFields as $field)
                        <div class="col-md-6 mb-3">
                            <label for="custom_field_{{ $field->id }}" class="form-label">
                                {{ $field->name }}
                                @if($field->is_required) <span class="text-danger">*</span> @endif
                            </label>

                            @if($field->type == 'text' || $field->type == 'input')
                                <input type="text"
                                       class="form-control @error('custom_fields.'.$field->id) is-invalid @enderror"
                                       id="custom_field_{{ $field->id }}"
                                       name="custom_fields[{{ $field->id }}]"
                                       value="{{ old('custom_fields.'.$field->id, $client->getCustomFieldValue($field->id)) }}"
                                       @if($field->is_required) required @endif>
                            @elseif($field->type == 'textarea')
                                <textarea class="form-control @error('custom_fields.'.$field->id) is-invalid @enderror"
                                          id="custom_field_{{ $field->id }}"
                                          name="custom_fields[{{ $field->id }}]"
                                          rows="3"
                                          @if($field->is_required) required @endif>{{ old('custom_fields.'.$field->id, $client->getCustomFieldValue($field->id)) }}</textarea>
                            @elseif($field->type == 'select')
                                <select class="form-select @error('custom_fields.'.$field->id) is-invalid @enderror"
                                        id="custom_field_{{ $field->id }}"
                                        name="custom_fields[{{ $field->id }}]"
                                        @if($field->is_required) required @endif>
                                    <option value="">{{ __('store.common_please_select') }}</option>
                                    @if(is_array($field->values))
                                        @foreach($field->values as $key => $value)
                                            <option value="{{ $key }}"
                                                    {{ old('custom_fields.'.$field->id, $client->getCustomFieldValue($field->id)) == $key ? 'selected' : '' }}>
                                                {{ $value }}
                                            </option>
                                        @endforeach
                                    @endif
                                </select>
                            @elseif($field->type == 'checkbox')
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox"
                                           id="custom_field_{{ $field->id }}"
                                           name="custom_fields[{{ $field->id }}]"
                                           value="1"
                                           {{ old('custom_fields.'.$field->id, $client->getCustomFieldValue($field->id)) ? 'checked' : '' }}>
                                    <label class="form-check-label" for="custom_field_{{ $field->id }}">
                                        {{ $field->description }}
                                    </label>
                                </div>
                            @endif

                            @if($field->description && $field->type != 'checkbox')
                                <div class="form-text">{{ $field->description }}</div>
                            @endif

                            @error('custom_fields.'.$field->id)
                                <div class="invalid-feedback d-block">{{ $message }}</div>
                            @enderror
                        </div>
                    @endforeach
                </div>
            @endif

            <!-- Action Buttons -->
            <div class="d-flex justify-content-between pt-3 border-top">
                <button type="button" class="btn btn-outline-secondary" onclick="history.back()">
                    {{ __('store.buttons_cancel') }}
                </button>
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-save me-2"></i>{{ __('store.buttons_save') }}
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Change Password -->
@if(!($isImpersonating ?? false))
<div class="card mt-4">
    <div class="card-header">
        <h5 class="mb-0">{{ __('store.clientarea_change_password') }}</h5>
    </div>
    <div class="card-body">
        @if (session('password_error') && $errors->has('current_password'))
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            {{ $errors->first('current_password') }}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        @endif

        <form method="POST" action="{{ route('store.auth.profile.change-password') }}" id="changePasswordForm">
            @csrf
            <div class="row">
                <div class="col-md-4 mb-3">
                    <label for="current_password" class="form-label">
                        {{ __('store.clientarea_profile_password_current') }} <span class="text-danger">*</span>
                    </label>
                    <input type="password" class="form-control" id="current_password" name="current_password" required>
                </div>
                <div class="col-md-4 mb-3">
                    <label for="new_password" class="form-label">
                        {{ __('store.clientarea_profile_password_new') }} <span class="text-danger">*</span>
                    </label>
                    <input type="password" class="form-control @error('new_password') is-invalid @enderror"
                           id="new_password" name="new_password" required minlength="8">
                    @error('new_password')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
                <div class="col-md-4 mb-3">
                    <label for="new_password_confirmation" class="form-label">
                        {{ __('store.clientarea_profile_password_confirm') }} <span class="text-danger">*</span>
                    </label>
                    <input type="password" class="form-control" id="new_password_confirmation" name="new_password_confirmation" required minlength="8">
                </div>
            </div>
            <div class="d-flex justify-content-end">
                <button type="submit" class="btn btn-warning">
                    <i class="fas fa-key me-2"></i>{{ __('store.clientarea_change_password') }}
                </button>
            </div>
        </form>
    </div>
</div>
@endif
@endsection

<!-- Window Variables for XHR -->
<script>
window.citiesEndpoint = '{{ url("storeapi/store/cities") }}';
window.currentCountryId = {{ $client->country_id ?? 'null' }};
window.currentCityId = {{ $client->city_id ?? 'null' }};
window.translations = window.translations || {};
window.translations.selectCity = '{{ __("store.auth_select_city") }}';
</script>

@push('profile-scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Initialize Bootstrap tooltips
    const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
    const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl));

    const countrySelect = document.getElementById('country_id');
    const citySelect = document.getElementById('city_id');

    if (countrySelect && citySelect) {
        // Function to load cities
        function loadCities(countryId, selectCityId = null) {
            // Clear cities
            citySelect.innerHTML = `<option value="">${window.translations?.selectCity || 'Select City'}</option>`;

            if (countryId) {
                fetch(`${window.citiesEndpoint}/${countryId}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.success && data.cities) {
                            data.cities.forEach(city => {
                                const option = document.createElement('option');
                                option.value = city.id;
                                option.textContent = city.name;
                                if (selectCityId && city.id == selectCityId) {
                                    option.selected = true;
                                }
                                citySelect.appendChild(option);
                            });
                        }
                    })
                    .catch(error => {
                        console.error('Error loading cities:', error);
                    });
            }
        }

        // Country change handler
        countrySelect.addEventListener('change', function() {
            loadCities(this.value);
        });

        // Load cities on page load if country is selected
        if (window.currentCountryId) {
            loadCities(window.currentCountryId, window.currentCityId);
        }
    }
});
</script>
@endpush