



<?php $__env->startSection('content'); ?>


<style>
    input:-webkit-autofill,
    input:-webkit-autofill:hover,
    input:-webkit-autofill:focus,
    input:-webkit-autofill:active {
        -webkit-box-shadow: 0 0 0 30px white inset !important;
        box-shadow: 0 0 0 30px white inset !important;
        -webkit-text-fill-color: #0F172A !important;
    }
</style>


<div id="main-wrapper" class="p-10">

  <div x-data="profileManager()" x-init="init(); cleanPhoneField(); $watch('user.phone', value => { if(value && (value.includes('@') || value.includes('.'))) { user.phone = ''; } });" class="flex flex-col gap-8 relative">

    
    <div x-show="processing" x-transition.opacity
      class="fixed inset-0 bg-black bg-opacity-80 z-50 flex items-center justify-center" style="display: none;">
      <div class="text-white text-lg flex flex-col items-center gap-2">
        <i class="fa-solid fa-spinner fa-spin text-4xl"></i>
        <span class="text-base"><?php echo e(trans('lang.processing')); ?></span>
      </div>
    </div>

    
    <div class="rounded-lg shadow-[1px_1px_4px_0px_#e2e8f0] p-6 bg-gradient-to-r from-slate-900 via-blue-800 to-blue-500 flex items-center justify-between">
        <div>
            <h3 class="text-2xl font-bold text-slate-50"><?php echo trans('lang.manage_profile'); ?></h3>
            <p class="text-sm text-slate-200 mt-1 m-0"><?php echo trans('lang.manage_profile_desc'); ?></p>
        </div>
        <a href="<?php echo e(route('user.profile')); ?>" class="px-4 py-2 rounded-md bg-white text-slate-700 text-sm hover:bg-slate-100 hover:text-slate-700 hover:no-underline transition focus:outline-none focus:ring-0 flex items-center gap-2">
            <i class="fa fa-rotate-left"></i>
            <?php echo e(trans('lang.back_to_account_settings')); ?>

        </a>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">

        
        <div class="rounded-lg border !border-slate-300 shadow-[1px_1px_4px_0px_#e2e8f0] overflow-hidden flex flex-col">
            <div class="bg-slate-900 px-6 py-4">
                <h3 class="text-xl font-bold text-white m-0"><?php echo trans('lang.profile_informations'); ?></h3>
            </div>
            <div class="p-6 bg-white flex flex-col gap-5 flex-grow">
                <div class="flex flex-col gap-6 flex-grow">
                    
                    <div>
                        <label class="block text-sm text-slate-500 font-medium mb-1"><?php echo e(trans('lang.first_name')); ?></label>
                        <input type="text" x-model="user.firstName"
                               @input="user.firstName = user.firstName.replace(/[^\p{L}\s-]/gu, '')" @blur="validateField('firstName')"
                               class="text-slate-700 border !border-slate-300 rounded-lg py-2 px-3 w-full transition duration-150 focus:outline-none focus:ring-0 focus:border-slate-300 focus:bg-blue-50"
                               :class="{ '!border-red-500': errors.firstName }">
                        <span x-show="errors.firstName" x-text="errors.firstName" class="text-red-500 text-sm mt-1" x-transition></span>
                    </div>
                    
                    <div>
                        <label class="block text-sm text-slate-500 font-medium mb-1"><?php echo e(trans('lang.last_name')); ?></label>
                        <input type="text" x-model="user.lastName"
                               @input="user.lastName = user.lastName.replace(/[^\p{L}\s-]/gu, '')" @blur="validateField('lastName')"
                               class="text-slate-700 border !border-slate-300 rounded-lg py-2 px-3 w-full transition duration-150 focus:outline-none focus:ring-0 focus:border-slate-300 focus:bg-blue-50"
                               :class="{ '!border-red-500': errors.lastName }">
                        <span x-show="errors.lastName" x-text="errors.lastName" class="text-red-500 text-sm mt-1" x-transition></span>
                    </div>
                    
                    <div>
                        <label class="block text-sm text-slate-500 font-medium mb-1"><?php echo e(trans('lang.email')); ?></label>
                        <input type="email" :value="user.email"
                               class="text-slate-700 border !border-slate-300 rounded-lg py-2 px-3 w-full bg-slate-100 cursor-not-allowed" disabled>
                    </div>
                    
                    <div>
                        <label class="block text-sm text-slate-500 font-medium mb-1"><?php echo e(trans('lang.user_phone')); ?></label>
                        <div class="flex items-center">
                            <div class="flex items-center justify-center px-4 h-11 border border-slate-300 rounded-l-lg bg-slate-100 text-slate-700">
                                <span>+49</span>
                            </div>
                            <input type="text" x-model="user.phone"
                                   @input="user.phone = user.phone.replace(/[^0-9\s]/g, ''); if(user.phone.includes('@') || user.phone.includes('.')) user.phone = '';"
                                   @blur="validateField('phone')"
                                   @focus="this.value = ''; user.phone = ''; console.log('Phone field focused, clearing value');"
                                   placeholder="<?php echo e(trans('lang.restaurant_phone_placeholder')); ?> (<?php echo e(trans('lang.optional')); ?>)"
                                   autocomplete="new-password"
                                   autocorrect="off"
                                   autocapitalize="off"
                                   spellcheck="false"
                                   data-form-type="other"
                                   data-lpignore="true"
                                   data-1p-ignore="true"
                                   name="phone_field_unique_<?php echo e(uniqid()); ?>"
                                   id="phone_field_unique_<?php echo e(uniqid()); ?>"
                                   readonly onfocus="this.removeAttribute('readonly');"
                                   class="text-slate-700 border !border-slate-300 rounded-r-lg py-2 px-3 flex-1 transition duration-150 focus:outline-none focus:ring-0 focus:border-slate-300 focus:bg-blue-50 -ml-px h-11"
                                   :class="{ '!border-red-500': errors.phone }">
                        </div>
                        <span x-show="errors.phone" x-text="errors.phone" class="text-red-500 text-sm mt-1" x-transition></span>

                    </div>
                    
                    <div>
                        <label class="block text-sm text-slate-500 font-medium mb-1"><?php echo e(trans('lang.profile_pic')); ?></label>
                        <div class="mt-2">
                            <input type="file" @change="selectFile($event.target.files[0])" id="profilePicInput" class="hidden" accept="image/png, image/jpeg, image/webp">
                            
                            <template x-if="!isUploading && (user.profilePicUrl || imagePreview)">
                                <div class="flex items-center gap-4">
                                    <img :src="imagePreview || user.profilePicUrl" alt="PodglÄ…d zdjÄ™cia"
                                        class="w-24 h-24 rounded-full object-cover border-2 border-slate-200">
                                    <div class="flex flex-col gap-3">
                                        
                                        <button @click="triggerFileInput()" type="button" class="flex items-center gap-2 px-3 py-2 text-sm text-slate-700 rounded-md hover:bg-blue-100 hover:text-blue-500 border !border-slate-300 transition focus:outline-none focus:ring-0">
                                            <i class="fa-solid fa-pencil text-xs"></i>
                                            <span><?php echo e(trans('lang.change_photo')); ?></span>
                                        </button>
                                        
                                        <button @click="removeImage()" type="button" class="flex items-center gap-2 px-3 py-2 text-sm text-slate-700 rounded-md hover:bg-red-100 hover:text-red-600 border !border-slate-300 transition focus:outline-none focus:ring-0">
                                            <i class="fa-solid fa-trash text-xs"></i>
                                            <span><?php echo e(trans('lang.remove_photo')); ?></span>
                                        </button>
                                    </div>
                                </div>
                            </template>
                            
                            <template x-if="isUploading">
                                <div class="w-full">
                                    <div class="w-full bg-slate-200 rounded-full h-8 p-1 relative overflow-hidden">
                                        <div class="bg-blue-500 h-full rounded-full flex items-center justify-end px-2 text-white text-xs font-bold transition-all duration-300"
                                            :style="`width: ${uploadProgress}%`">
                                            <span x-text="`${Math.round(uploadProgress)}%`"></span>
                                        </div>
                                    </div>
                                    <button @click="cancelUpload()" title="<?php echo e(trans('lang.cancel_upload')); ?>" class="w-full text-center mt-2 text-sm text-slate-600 hover:text-black focus:outline-none focus:ring-0">
                                        <?php echo e(trans('lang.cancel')); ?>

                                    </button>
                                </div>
                            </template>
                            
                            <template x-if="!isUploading && !user.profilePicUrl && !imagePreview">
                                <div @click="triggerFileInput()" @dragover.prevent="isDragging = true"
                                    @dragleave.prevent="isDragging = false"
                                    @drop.prevent="isDragging = false; selectFile($event.dataTransfer.files[0])"
                                    class="w-full p-6 border-2 border-dashed border-slate-300 rounded-lg text-center cursor-pointer transition-colors"
                                    :class="{'bg-blue-50 border-blue-400': isDragging}">
                                    <div class="flex flex-col items-center justify-center gap-2 text-slate-500">
                                        <i class="fa-solid fa-cloud-arrow-up text-3xl"></i>
                                        <p class="font-semibold"><?php echo e(trans('lang.drag_and_drop_file_here')); ?></p>
                                        <p class="text-sm"><?php echo e(trans('lang.or')); ?></p>
                                        <p class="font-semibold text-blue-500"><?php echo e(trans('lang.click_to_select_from_disk')); ?></p>
                                        <p class="text-xs text-slate-400 mt-2"><?php echo e(trans('lang.uploader_file_types_info')); ?></p>
                                    </div>
                                </div>
                            </template>
                            <p x-show="uploadError" x-text="uploadError" class="text-sm text-red-600 mt-2"></p>
                        </div>
                    </div>
                </div>
                
                <button type="button" @click="saveProfile" :disabled="isProfileUnchanged || isProfileFormInvalid"
                        class="uppercase w-full mt-auto bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 transition disabled:opacity-50 disabled:cursor-not-allowed focus:outline-none focus:ring-0">
                    <?php echo e(trans('lang.submit')); ?>

                </button>
            </div>
        </div>

        
        <div class="rounded-lg border !border-slate-300 shadow-[1px_1px_4px_0px_#e2e8f0] overflow-hidden flex flex-col">
            <div class="bg-slate-900 px-6 py-4">
                <h3 class="text-xl font-bold text-white m-0"><?php echo e(trans('lang.change_password')); ?></h3>
            </div>
            <div class="p-6 bg-white flex flex-col gap-5 flex-grow">
                <div class="flex flex-col gap-6 flex-grow">
                    
                    <div>
                        <label class="block text-sm text-slate-500 font-medium mb-1"><?php echo e(trans('lang.old_password')); ?></label>
                        <div class="relative">
                            <input :type="passwordVisibility.old ? 'text' : 'password'" x-model="password.old" @blur="validateField('passwordOld')"
                                class="text-slate-700 border !border-slate-300 rounded-lg py-2 px-3 w-full transition duration-150 focus:outline-none focus:ring-0 focus:border-slate-300 focus:bg-blue-50 pr-10"
                                :class="{ '!border-red-500': errors.passwordOld }" autocomplete="current-password">
                            <button type="button" @click="passwordVisibility.old = !passwordVisibility.old" class="absolute inset-y-0 right-0 px-3 flex items-center text-slate-500 hover:text-slate-700 focus:outline-none focus:ring-0">
                                <i class="fa-solid" :class="passwordVisibility.old ? 'fa-eye-slash' : 'fa-eye'"></i>
                            </button>
                        </div>
                        <span x-show="errors.passwordOld" x-text="errors.passwordOld" class="text-red-500 text-sm mt-1" x-transition></span>
                    </div>
                    
                    <div>
                        <label class="block text-sm text-slate-500 font-medium mb-1"><?php echo e(trans('lang.new_password')); ?></label>
                        <div class="relative">
                            <input :type="passwordVisibility.new ? 'text' : 'password'" x-model="password.new" @input="validatePasswordRealtime()"
                                class="text-slate-700 border !border-slate-300 rounded-lg py-2 px-3 w-full transition duration-150 focus:outline-none focus:ring-0 focus:border-slate-300 focus:bg-blue-50 pr-10"
                                :class="{ '!border-red-500': passwordStrength.score > 0 && passwordStrength.score < 4 }" autocomplete="new-password">
                            <button type="button" @click="passwordVisibility.new = !passwordVisibility.new" class="absolute inset-y-0 right-0 px-3 flex items-center text-slate-500 hover:text-slate-700 focus:outline-none focus:ring-0">
                                <i class="fa-solid" :class="passwordVisibility.new ? 'fa-eye-slash' : 'fa-eye'"></i>
                            </button>
                        </div>
                        
                        <div class="mt-3 space-y-3" x-show="password.new.length > 0" x-transition>
                            <div class="flex items-center gap-2">
                                <div class="w-full bg-slate-200 rounded-full h-2">
                                    <div class="h-2 rounded-full transition-all"
                                         :class="{
                                            'bg-red-500 w-1/4': passwordStrength.score <= 1,
                                            'bg-orange-500 w-2/4': passwordStrength.score === 2,
                                            'bg-yellow-500 w-3/4': passwordStrength.score === 3,
                                            'bg-green-500 w-full': passwordStrength.score >= 4,
                                         }"></div>
                                </div>
                                <span class="text-sm font-semibold"
                                      :class="{
                                        'text-red-500': passwordStrength.score <= 1,
                                        'text-orange-500': passwordStrength.score === 2,
                                        'text-yellow-500': passwordStrength.score === 3,
                                        'text-green-500': passwordStrength.score >= 4,
                                      }"
                                      x-text="passwordStrength.text"></span>
                            </div>
                            <div class="grid grid-cols-1 sm:grid-cols-2 text-sm">
                                <div class="flex items-center gap-2" :class="passwordRequirements.length ? 'text-green-600' : 'text-slate-500'">
                                    <i class="fa-solid fa-sm" :class="passwordRequirements.length ? 'fa-check' : 'fa-times'"></i>
                                    <span><?php echo e(trans('lang.password_req_length')); ?></span>
                                </div>
                                <div class="flex items-center gap-2" :class="passwordRequirements.uppercase ? 'text-green-600' : 'text-slate-500'">
                                    <i class="fa-solid fa-sm" :class="passwordRequirements.uppercase ? 'fa-check' : 'fa-times'"></i>
                                    <span><?php echo e(trans('lang.password_req_uppercase')); ?></span>
                                </div>
                                <div class="flex items-center gap-2" :class="passwordRequirements.lowercase ? 'text-green-600' : 'text-slate-500'">
                                    <i class="fa-solid fa-sm" :class="passwordRequirements.lowercase ? 'fa-check' : 'fa-times'"></i>
                                    <span><?php echo e(trans('lang.password_req_lowercase')); ?></span>
                                </div>
                                <div class="flex items-center gap-2" :class="passwordRequirements.number ? 'text-green-600' : 'text-slate-500'">
                                    <i class="fa-solid fa-sm" :class="passwordRequirements.number ? 'fa-check' : 'fa-times'"></i>
                                    <span><?php echo e(trans('lang.password_req_number')); ?></span>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div>
                         <label class="block text-sm text-slate-500 font-medium mb-1"><?php echo e(trans('lang.confirm_password')); ?></label>
                         <div class="relative">
                            <input :type="passwordVisibility.confirm ? 'text' : 'password'" x-model="password.confirm" @input="validateConfirmation()"
                                   class="text-slate-700 border !border-slate-300 rounded-lg py-2 px-3 w-full transition duration-150 focus:outline-none focus:ring-0 focus:border-slate-300 focus:bg-blue-50 pr-10"
                                   :class="{ '!border-red-500': passwordConfirmationError }" autocomplete="new-password">
                            <button type="button" @click="passwordVisibility.confirm = !passwordVisibility.confirm" class="absolute inset-y-0 right-0 px-3 flex items-center text-slate-500 hover:text-slate-700 focus:outline-none focus:ring-0">
                                <i class="fa-solid" :class="passwordVisibility.confirm ? 'fa-eye-slash' : 'fa-eye'"></i>
                            </button>
                        </div>
                        <span x-show="passwordConfirmationError" x-text="passwordConfirmationError" class="text-red-500 text-sm mt-1" x-transition></span>
                    </div>
                </div>
                
                <button type="button" @click="changePassword" :disabled="isPasswordFormInvalid"
                        class="uppercase w-full mt-auto bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 transition disabled:opacity-50 disabled:cursor-not-allowed focus:outline-none focus:ring-0">
                    <?php echo e(trans('lang.change_password')); ?>

                </button>
            </div>
        </div>
    </div>

    
    <div x-show="notification.show" x-transition class="fixed top-5 right-5 z-50 max-w-lg w-full rounded-lg shadow-lg pointer-events-auto" :class="{ 'bg-green-100 border-l-4 border-green-500': notification.type === 'success', 'bg-red-100 border-l-4 border-red-500': notification.type === 'error' }" style="display: none;">
        <div class="p-4">
            <div class="grid grid-cols-[auto,1fr,auto] items-center gap-x-3">
                <div class="flex-shrink-0">
                    <i x-show="notification.type === 'success'"
                        class="fa-solid fa-check-circle text-green-500 text-xl"></i>
                    <i x-show="notification.type === 'error'"
                        class="fa-solid fa-times-circle text-red-500 text-xl"></i>
                </div>
                <div>
                    <p class="text-sm font-medium break-words"
                        :class="{ 'text-green-800': notification.type === 'success', 'text-red-800': notification.type === 'error' }"
                        x-text="notification.message"></p>
                </div>
                <div class="flex-shrink-0">
                    <button @click="notification.show = false" class="inline-flex text-slate-500 hover:text-slate-600 focus:outline-none focus:ring-0">
                        <span class="sr-only"><?php echo e(trans('lang.close')); ?></span>
                        <i class="fa-solid fa-times"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>

  </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('scripts'); ?>
<style>
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active {
    -webkit-box-shadow: 0 0 0 30px white inset !important;
    box-shadow: 0 0 0 30px white inset !important;
    -webkit-text-fill-color: #0F172A !important;
}
input[name*="phone"]::-webkit-contacts-auto-fill-button,
input[name*="phone"]::-webkit-credentials-auto-fill-button {
    display: none !important;
    visibility: hidden !important;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/compressorjs/1.1.1/compressor.min.js"></script>
<script>
function profileManager() {
    return {
        processing: true,
        notification: { show: false, type: 'success', message: '' },
        errors: {},
        imagePreview: null,
        isUploading: false,
        uploadProgress: 0,
        uploadError: '',
        isDragging: false,
        passwordVisibility: { old: false, new: false, confirm: false },
        passwordRequirements: { length: false, uppercase: false, lowercase: false, number: false },
        passwordStrength: { score: 0, text: '' },
        passwordConfirmationError: '',
        vendorUserId: "<?php echo $id; ?>",
        isEmployee: <?php echo e($isEmployee ? 'true' : 'false'); ?>,
        <?php if($isEmployee && $employeeData): ?>
        employeeData: {
            firstName: "<?php echo e($employeeData->name); ?>",
            lastName: "<?php echo e($employeeData->surname); ?>",
            email: "<?php echo e($employeeData->email); ?>",
            phone: "",
            phonePrefix: "+49",
            profilePicUrl: "<?php echo e($employeeData->profile_picture ?? ''); ?>"
        },
        <?php endif; ?>
        user: { firstName: '', lastName: '', email: '', phone: '', phonePrefix: '+49', profilePicUrl: '' },
        password: { old: '', new: '', confirm: '' },
        originalUser: {},

        get isProfileUnchanged() { return JSON.stringify(this.user) === JSON.stringify(this.originalUser); },
        get isProfileFormInvalid() {
            return !!(this.errors.firstName || this.errors.lastName || this.errors.phone);
        },
        get isPasswordFormInvalid() {
            const allReqsMet = Object.values(this.passwordRequirements).every(val => val === true);
            return !this.password.old || !allReqsMet || this.password.new !== this.password.confirm;
        },

        cleanPhoneField() {
            if (this.user.phone && this.user.phone.includes('@')) {
                this.user.phone = '';
            }
        },
        triggerFileInput() { document.getElementById('profilePicInput').click(); },
        removeImage() {
            this.user.profilePicUrl = '';
            this.imagePreview = null;
            document.getElementById('profilePicInput').value = '';
            Alpine.store('user').avatar = '<?php echo e(asset('images/icons/account_icon.svg')); ?>';
        },
        cancelUpload() {
            this.isUploading = false; this.uploadProgress = 0; this.imagePreview = null;
        },
        selectFile(file) {
            if (!file) { this.uploadError = ''; return; }
            const allowedTypes = ['image/png', 'image/jpeg', 'image/webp'];
            if (!allowedTypes.includes(file.type)) {
                this.uploadError = '<?php echo e(trans("lang.uploader_file_type_error")); ?>'; return;
            }
            const maxSizeInMB = 5;
            if (file.size > maxSizeInMB * 1024 * 1024) {
                this.uploadError = '<?php echo e(trans("lang.uploader_file_size_error")); ?> ' + maxSizeInMB + 'MB.'; return;
            }
            this.uploadError = '';
            this.imagePreview = URL.createObjectURL(file);
            this.startUpload(file);
        },
        startUpload(file) {
            this.isUploading = true; this.uploadProgress = 0;
            if (this.isEmployee) {
                this.uploadEmployeeProfilePicture(file);
            } else {
                this.uploadVendorProfilePicture(file);
            }
        },
        uploadEmployeeProfilePicture(file) {
            new Compressor(file, {
                quality: 0.8, maxWidth: 1024,
                success: async (compressedResult) => {
                    try {
                        const formData = new FormData();
                        formData.append('profile_picture', compressedResult);
                        const progressInterval = setInterval(() => {
                            if (this.uploadProgress < 90) this.uploadProgress += 10;
                        }, 100);
                        const response = await fetch('/api/employee/profile-picture', {
                            method: 'POST',
                            headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content') },
                            body: formData
                        });
                        clearInterval(progressInterval);
                        this.uploadProgress = 100;
                        const result = await response.json();
                        if (!response.ok) throw new Error(result.error || 'Failed to upload profile picture');
                        this.user.profilePicUrl = result.profile_picture_url;
                        this.isUploading = false; this.imagePreview = null;
                        Alpine.store('user').avatar = result.profile_picture_url;
                        this.showNotification('<?php echo e(trans("lang.photo_updated_success")); ?>', 'success');
                    } catch (error) {
                        this.showNotification('<?php echo e(trans("lang.upload_error")); ?>: ' + error.message, 'error');
                        this.isUploading = false; this.imagePreview = null;
                    }
                },
                error: (err) => {
                    this.showNotification('<?php echo e(trans("lang.compression_error")); ?>: ' + err.message, 'error');
                    this.isUploading = false;
                },
            });
        },
        uploadVendorProfilePicture(file) {
            new Compressor(file, {
                quality: 0.8, maxWidth: 1024,
                success: async (compressedResult) => {
                    try {
                        const formData = new FormData();
                        formData.append('photo', compressedResult, 'profile.jpg');
                        const progressInterval = setInterval(() => {
                            if (this.uploadProgress < 90) this.uploadProgress += 10;
                        }, 100);
                        const response = await fetch('/api/profile/photo', {
                            method: 'POST',
                            headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content') },
                            body: formData
                        });
                        clearInterval(progressInterval);
                        this.uploadProgress = 100;
                        const result = await response.json();
                        if (!response.ok) throw new Error(result.message || 'Failed to upload photo');
                        this.user.profilePicUrl = result.url;
                        this.isUploading = false; this.imagePreview = null;
                        Alpine.store('user').avatar = result.url;
                        this.showNotification('<?php echo e(trans("lang.photo_updated_success")); ?>', 'success');
                    } catch (error) {
                        this.showNotification('<?php echo e(trans("lang.upload_error")); ?>: ' + error.message, 'error');
                        this.isUploading = false; this.imagePreview = null;
                    }
                },
                error: (err) => {
                    this.showNotification('<?php echo e(trans("lang.compression_error")); ?>: ' + err.message, 'error');
                    this.isUploading = false;
                },
            });
        },
        validateField(field) {
            switch(field) {
                case 'firstName':
                    if (!this.user.firstName.trim()) {
                        this.errors.firstName = '<?php echo e(trans("lang.first_name_error")); ?>';
                    } else if (/[^\p{L}\s-]/u.test(this.user.firstName)) {
                        this.errors.firstName = '<?php echo e(trans("lang.first_name_invalid_error")); ?>';
                    } else { delete this.errors.firstName; }
                    break;
                case 'lastName':
                    if (!this.user.lastName.trim()) {
                        this.errors.lastName = '<?php echo e(trans("lang.last_name_error")); ?>';
                    } else if (/[^\p{L}\s-]/u.test(this.user.lastName)) {
                        this.errors.lastName = '<?php echo e(trans("lang.last_name_invalid_error")); ?>';
                    } else { delete this.errors.lastName; }
                    break;
                case 'phone':
                    const phoneRegex = /^\d{7,15}$/;
                    const cleanedPhone = this.user.phone.replace(/\s/g, '');
                    if (cleanedPhone && !phoneRegex.test(cleanedPhone)) {
                        this.errors.phone = '<?php echo e(trans("lang.phone_number_invalid_error")); ?>';
                    } else {
                        delete this.errors.phone;
                    }
                    break;
                case 'passwordOld':
                    if (!this.password.old) this.errors.passwordOld = '<?php echo e(trans("lang.old_password_error")); ?>';
                    else delete this.errors.passwordOld;
                    break;
            }
        },
        validatePasswordRealtime() {
            const pass = this.password.new;
            this.passwordRequirements.length    = pass.length >= 8;
            this.passwordRequirements.uppercase = /[A-Z]/.test(pass);
            this.passwordRequirements.lowercase = /[a-z]/.test(pass);
            this.passwordRequirements.number    = /[0-9]/.test(pass);
            let score = Object.values(this.passwordRequirements).filter(Boolean).length;
            this.passwordStrength.score = score;
            const strengthLevels = {
                0: '<?php echo e(trans("lang.password_strength_very_weak")); ?>',
                1: '<?php echo e(trans("lang.password_strength_weak")); ?>',
                2: '<?php echo e(trans("lang.password_strength_medium")); ?>',
                3: '<?php echo e(trans("lang.password_strength_strong")); ?>',
                4: '<?php echo e(trans("lang.password_strength_very_strong")); ?>',
            };
            this.passwordStrength.text = strengthLevels[score] || '';
            this.validateConfirmation();
        },
        validateConfirmation() {
            if (this.password.confirm && this.password.new !== this.password.confirm) {
                this.passwordConfirmationError = '<?php echo e(trans("lang.confirm_password_error")); ?>';
            } else { this.passwordConfirmationError = ''; }
        },
        showNotification(message, type = 'success', duration = 4000) {
            this.notification.message = message;
            this.notification.type    = type;
            this.notification.show    = true;
            setTimeout(() => { this.notification.show = false; }, duration);
        },
        async init() {
            this.processing = true;
            try {
                if (this.isEmployee && this.employeeData) {
                    let cleanPhone = this.employeeData.phone || '';
                    if (cleanPhone && cleanPhone.includes('@')) cleanPhone = '';
                    this.user = {
                        firstName:     this.employeeData.firstName,
                        lastName:      this.employeeData.lastName,
                        email:         this.employeeData.email,
                        phone:         cleanPhone,
                        phonePrefix:   this.employeeData.phonePrefix,
                        profilePicUrl: this.employeeData.profilePicUrl,
                    };
                    this.originalUser = JSON.parse(JSON.stringify(this.user));
                    this.cleanPhoneField();
                    this.processing = false;
                    return;
                }

                const response = await fetch('/api/profile', {
                    headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content') }
                });
                if (!response.ok) throw new Error('Failed to load profile data.');
                const data = await response.json();
                this.user = {
                    firstName:     data.firstName     || '',
                    lastName:      data.lastName      || '',
                    email:         data.email         || '',
                    phone:         data.phone         || '',
                    phonePrefix:   '+49',
                    profilePicUrl: data.profilePicUrl || '',
                };
                this.originalUser = JSON.parse(JSON.stringify(this.user));
            } catch (error) {
                this.showNotification('<?php echo e(trans("lang.data_load_error")); ?>: ' + error.message, 'error');
                console.error(error);
            } finally {
                this.processing = false;
                if (document.activeElement) document.activeElement.blur();
            }
        },
        async saveProfile() {
            this.validateField('firstName'); this.validateField('lastName'); this.validateField('phone');
            if (Object.keys(this.errors).length > 0) {
                this.showNotification('<?php echo e(trans("lang.form_errors_correct_them")); ?>', 'error'); return;
            }
            if (this.isProfileUnchanged) return;
            this.processing = true;
            try {
                const endpoint = this.isEmployee ? '/api/employee/profile' : '/api/profile';
                const payload  = this.isEmployee
                    ? { firstName: this.user.firstName, lastName: this.user.lastName, phone: this.user.phone || null }
                    : { firstName: this.user.firstName, lastName: this.user.lastName, phone: this.user.phone || null, profilePicUrl: this.user.profilePicUrl };

                const response = await fetch(endpoint, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                    },
                    body: JSON.stringify(payload)
                });
                const result = await response.json();
                if (!response.ok) throw new Error(result.error || result.message || 'Failed to update profile');
                this.originalUser = JSON.parse(JSON.stringify(this.user));
                Alpine.store('user').avatar = this.user.profilePicUrl
                    ? this.user.profilePicUrl
                    : '<?php echo e(asset('images/icons/account_icon.svg')); ?>';
                this.showNotification('<?php echo e(trans("lang.profile_saved_success")); ?>', 'success');
            } catch (error) {
                this.showNotification('<?php echo e(trans("lang.data_save_error")); ?>: ' + error.message, 'error');
            } finally {
                this.processing = false;
            }
        },
        async changePassword() {
            if (this.isPasswordFormInvalid) {
                this.showNotification('<?php echo e(trans("lang.form_errors_correct_them")); ?>', 'error');
                return;
            }
            this.processing = true;
            try {
                const endpoint = this.isEmployee ? '/api/employee/change-password' : '/api/profile/change-password';
                const response = await fetch(endpoint, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                    },
                    body: JSON.stringify({ old_password: this.password.old, new_password: this.password.new })
                });
                const result = await response.json();
                if (!response.ok) throw new Error(result.error || result.message || 'Failed to change password');
                this.showNotification('<?php echo e(trans("lang.password_changed_success")); ?>', 'success');
                this.password = { old: '', new: '', confirm: '' };
                this.validatePasswordRealtime();
            } catch (error) {
                this.showNotification('<?php echo e(trans("lang.password_change_error")); ?>: ' + error.message, 'error');
            } finally {
                this.processing = false;
            }
        }
    }
}
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\xampp\htdocs\pub-and-go-merchant-np\resources\views/users/manage_profile.blade.php ENDPATH**/ ?>