<?php $__env->startSection('content'); ?>
<style>
/* Colores personalizados basados en Blulinc */
:root {
    --blulinc-black: #000000;
    --blulinc-blue: #015cff;
    --blulinc-gray: #c1c1c1;
    --blulinc-light-gray: #f8f9fa;
    --blulinc-light-blue: #e6f2ff;
    --blulinc-bg-blue: #f0f7ff;
}

body {
    background-color: var(--blulinc-bg-blue) !important;
}

    .container {
        max-width: 700px;
        margin: 0 auto;
        padding: 16px 12px;
        width: 95%;
    }

    .blulinc-card {
        background: white;
        border-radius: 12px;
        box-shadow: 0 4px 16px rgba(1, 92, 255, 0.1);
        border: 1px solid #e1ecf7;
        margin-top: 12px;
    }

    .blulinc-card-header {
        background: linear-gradient(135deg, #015cff 0%, #0146cc 100%);
        color: white;
        padding: 16px 20px;
        font-size: 20px;
        font-weight: 600;
        text-align: center;
        border-radius: 12px 12px 0 0;
    }

    .blulinc-card-body {
        padding: 20px;
    }

    .form-group {
        margin-bottom: 16px;
    }

    .form-label {
        font-weight: 600;
        color: var(--blulinc-black);
        margin-bottom: 4px;
        display: block;
        font-size: 13px;
    }

    .form-control, .form-select {
        border: 2px solid #e1ecf7;
        border-radius: 6px;
        padding: 10px 14px;
        font-size: 13px;
        transition: all 0.3s ease;
        width: 100%;
    }

    .form-control:focus, .form-select:focus {
        border-color: var(--blulinc-blue);
        box-shadow: 0 0 0 3px rgba(1, 92, 255, 0.1);
        outline: none;
    }

    .btn-primary {
        background: linear-gradient(135deg, #015cff 0%, #0146cc 100%);
        border: none;
        color: white;
        padding: 10px 20px;
        border-radius: 6px;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        transition: all 0.3s ease;
        width: 100%;
        font-size: 13px;
    }

    .btn-primary:hover {
        background: linear-gradient(135deg, #0146cc 0%, #013299 100%);
        transform: translateY(-1px);
        box-shadow: 0 4px 16px rgba(1, 92, 255, 0.25);
        color: white;
    }

    .btn-secondary {
        background: white;
        border: 2px solid var(--blulinc-gray);
        color: var(--blulinc-black);
        padding: 8px 18px;
        border-radius: 6px;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        transition: all 0.3s ease;
        width: 100%;
        margin-top: 8px;
        font-size: 13px;
    }

    .btn-secondary:hover {
        background-color: var(--blulinc-light-blue);
        border-color: var(--blulinc-blue);
        color: var(--blulinc-blue);
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(1, 92, 255, 0.15);
    }

    /* Estilos para clases blulinc- específicas */
    .blulinc-container {
        max-width: 700px;
        margin: 0 auto;
        padding: 16px 12px;
        width: 95%;
        min-height: 100vh;
    }

    .blulinc-form-container {
        max-width: 100%;
        margin: 0 auto;
    }

    .blulinc-form-group {
        margin-bottom: 16px;
    }

    .blulinc-form-label {
        font-weight: 600;
        color: var(--blulinc-black);
        margin-bottom: 4px;
        display: block;
        font-size: 13px;
    }

    .blulinc-form-control, .blulinc-form-select {
        border: 2px solid #e1ecf7;
        border-radius: 6px;
        padding: 10px 14px;
        font-size: 13px;
        transition: all 0.3s ease;
        width: 100%;
        background-color: white;
    }

    .blulinc-form-control:focus, .blulinc-form-select:focus {
        border-color: var(--blulinc-blue);
        box-shadow: 0 0 0 3px rgba(1, 92, 255, 0.1);
        outline: none;
    }

    .blulinc-btn-primary {
        background: linear-gradient(135deg, #015cff 0%, #0146cc 100%);
        border: none;
        color: white;
        padding: 10px 20px;
        border-radius: 6px;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        transition: all 0.3s ease;
        width: 100%;
        font-size: 13px;
        text-decoration: none;
        display: inline-block;
        text-align: center;
    }

    .blulinc-btn-primary:hover {
        background: linear-gradient(135deg, #0146cc 0%, #013299 100%);
        transform: translateY(-1px);
        box-shadow: 0 4px 16px rgba(1, 92, 255, 0.25);
        color: white;
        text-decoration: none;
    }

    .blulinc-btn-secondary {
        background: white;
        border: 2px solid var(--blulinc-gray);
        color: var(--blulinc-black);
        padding: 8px 18px;
        border-radius: 6px;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        transition: all 0.3s ease;
        width: 100%;
        margin-top: 8px;
        font-size: 13px;
        text-decoration: none;
        display: inline-block;
        text-align: center;
    }

    .blulinc-btn-secondary:hover {
        background-color: var(--blulinc-light-blue);
        border-color: var(--blulinc-blue);
        color: var(--blulinc-blue);
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(1, 92, 255, 0.15);
        text-decoration: none;
    }

    .blulinc-alert-danger {
        background-color: #fef2f2;
        border: 2px solid #fca5a5;
        border-radius: 6px;
        padding: 8px 12px;
        margin-bottom: 16px;
        color: #dc2626;
        font-size: 12px;
    }

    .blulinc-alert-danger ul {
        margin: 0;
        padding-left: 20px;
    }

    .blulinc-search-container {
        position: relative;
        display: flex;
        align-items: center;
    }

    .blulinc-search-input {
        padding-right: 40px;
        border: 2px solid #e1ecf7;
        border-radius: 6px;
        padding: 10px 14px;
        font-size: 13px;
        transition: all 0.3s ease;
        width: 100%;
    }

    .blulinc-search-input:focus {
        border-color: var(--blulinc-blue);
        box-shadow: 0 0 0 3px rgba(1, 92, 255, 0.1);
        outline: none;
    }

    .blulinc-search-icon {
        position: absolute;
        right: 12px;
        color: var(--blulinc-gray);
        font-size: 16px;
        pointer-events: none;
        transition: color 0.2s ease;
    }

    .blulinc-search-input:focus + .blulinc-search-icon {
        color: var(--blulinc-blue);
    }

    .blulinc-form-text {
        color: var(--blulinc-gray);
        font-size: 11px;
        margin-top: 4px;
        font-weight: 500;
        line-height: 1.3;
    }

    .blulinc-form-check {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 16px;
    }

    .blulinc-form-check-input {
        width: 18px;
        height: 18px;
        border: 1px solid #dee2e6;
        border-radius: 4px;
        transition: all 0.2s ease;
    }

    .blulinc-form-check-input:checked {
        background-color: var(--blulinc-blue);
        border-color: var(--blulinc-blue);
    }

    .blulinc-form-check-label {
        color: var(--blulinc-black);
        font-weight: 500;
        font-size: 13px;
    }

    .button-group {
        display: flex;
        gap: 10px;
        margin-top: 20px;
    }

/* === MEDIA QUERIES PARA RESPONSIVIDAD === */

/* Pantallas muy grandes (1920px+) */
@media (min-width: 1920px) {
    .blulinc-container, .container {
        max-width: 800px;
        padding: 20px 16px;
    }
    .blulinc-card-header {
        font-size: 22px;
        padding: 18px 24px;
    }
    .blulinc-card-body {
        padding: 24px;
    }
    .blulinc-form-label, .form-label {
        font-size: 14px;
    }
    .blulinc-form-control, .blulinc-form-select, .form-control, .form-select {
        padding: 12px 16px;
        font-size: 14px;
    }
    .blulinc-btn-primary, .blulinc-btn-secondary, .btn-primary, .btn-secondary {
        padding: 12px 24px;
        font-size: 14px;
    }
}

/* Pantallas grandes (1200px - 1919px) */
@media (max-width: 1919px) and (min-width: 1200px) {
    .blulinc-container, .container {
        max-width: 650px;
    }
}

/* Pantallas medianas (768px - 1199px) */
@media (max-width: 1199px) and (min-width: 768px) {
    .blulinc-container, .container {
        padding: 12px 8px;
        max-width: 600px;
    }
    .blulinc-card-header {
        font-size: 18px;
        padding: 14px 16px;
    }
    .blulinc-card-body {
        padding: 16px;
    }
    .blulinc-form-group, .form-group {
        margin-bottom: 14px;
    }
    .blulinc-form-label, .form-label {
        font-size: 12px;
        margin-bottom: 3px;
    }
    .blulinc-form-control, .blulinc-form-select, .form-control, .form-select {
        padding: 8px 12px;
        font-size: 12px;
    }
    .blulinc-btn-primary, .blulinc-btn-secondary, .btn-primary, .btn-secondary {
        padding: 8px 16px;
        font-size: 12px;
    }
    .button-group {
        margin-top: 16px;
        gap: 8px;
    }
}

/* Pantallas pequeñas (576px - 767px) */
@media (max-width: 767px) and (min-width: 576px) {
    .blulinc-container, .container {
        padding: 8px 4px;
        width: 100%;
    }
    .blulinc-card-header {
        font-size: 16px;
        padding: 12px 14px;
    }
    .blulinc-card-body {
        padding: 14px;
    }
    .blulinc-form-group, .form-group {
        margin-bottom: 12px;
    }
    .blulinc-form-label, .form-label {
        font-size: 11px;
        margin-bottom: 2px;
    }
    .blulinc-form-control, .blulinc-form-select, .form-control, .form-select {
        padding: 7px 10px;
        font-size: 11px;
    }
    .blulinc-btn-primary, .blulinc-btn-secondary, .btn-primary, .btn-secondary {
        padding: 7px 14px;
        font-size: 11px;
    }
    .button-group {
        margin-top: 14px;
        gap: 6px;
    }
    .blulinc-form-text {
        font-size: 10px;
    }
}

/* Pantallas muy pequeñas (hasta 575px) */
@media (max-width: 575px) {
    .blulinc-container, .container {
        padding: 6px 2px;
        width: 100%;
    }
    .blulinc-card {
        border-radius: 8px;
    }
    .blulinc-card-header {
        font-size: 14px;
        padding: 10px 12px;
    }
    .blulinc-card-body {
        padding: 12px;
    }
    .blulinc-form-group, .form-group {
        margin-bottom: 10px;
    }
    .blulinc-form-label, .form-label {
        font-size: 10px;
        margin-bottom: 2px;
    }
    .blulinc-form-control, .blulinc-form-select, .form-control, .form-select {
        padding: 6px 8px;
        font-size: 10px;
    }
    .blulinc-btn-primary, .blulinc-btn-secondary, .btn-primary, .btn-secondary {
        padding: 6px 12px;
        font-size: 10px;
    }
    .button-group {
        margin-top: 12px;
        gap: 4px;
    }
    .blulinc-form-text {
        font-size: 9px;
    }
    .blulinc-alert-danger {
        padding: 6px 8px;
        margin-bottom: 12px;
        font-size: 10px;
    }
}

/* Pantallas ultra pequeñas (hasta 400px) */
@media (max-width: 400px) {
    .blulinc-container, .container {
        padding: 4px 1px;
    }
    .blulinc-card-header {
        font-size: 13px;
        padding: 8px 10px;
    }
    .blulinc-card-body {
        padding: 10px;
    }
    .blulinc-form-group, .form-group {
        margin-bottom: 8px;
    }
    .blulinc-form-label, .form-label {
        font-size: 9px;
        margin-bottom: 1px;
    }
    .blulinc-form-control, .blulinc-form-select, .form-control, .form-select {
        padding: 5px 6px;
        font-size: 9px;
    }
    .blulinc-btn-primary, .blulinc-btn-secondary, .btn-primary, .btn-secondary {
        padding: 5px 10px;
        font-size: 9px;
    }
    .button-group {
        margin-top: 10px;
        gap: 3px;
    }
    .blulinc-form-text {
        font-size: 8px;
    }
    .blulinc-alert-danger {
        padding: 5px 6px;
        margin-bottom: 10px;
        font-size: 9px;
    }
}
</style>

<div class="blulinc-container">
    <div class="blulinc-form-container">
        <div class="blulinc-card">
            <div class="blulinc-card-header">
                <h4><i class="bi bi-person-gear me-2"></i>Edit User</h4>
            </div>
            <div class="blulinc-card-body">
                <?php if($errors->any()): ?>
                    <div class="blulinc-alert-danger">
                        <ul>
                            <?php $__currentLoopData = $errors->all(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $error): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <li><?php echo e($error); ?></li>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </ul>
                    </div>
                <?php endif; ?>
                
                <form method="POST" action="<?php echo e(route('user-management.update', $user->id)); ?>">
                    <?php echo csrf_field(); ?>
                    <?php echo method_field('PUT'); ?>
                    
                    <div class="blulinc-form-group">
                        <label for="name" class="blulinc-form-label">Name</label>
                        <input type="text" class="blulinc-form-control" id="name" name="name" value="<?php echo e(old('name', $user->name)); ?>" required>
                    </div>
                    
                    <div class="blulinc-form-group">
                        <label for="email" class="blulinc-form-label">Email</label>
                        <input type="email" class="blulinc-form-control" id="email" name="email" value="<?php echo e(old('email', $user->email)); ?>" required>
                    </div>
                    
                    <div class="blulinc-form-group" id="partner-field-container">
                        <label for="partner_id" class="blulinc-form-label">
                            <i class="bi bi-building me-1"></i>Primary Partner
                        </label>
                        <div class="blulinc-search-container">
                            <input type="text" class="blulinc-form-control blulinc-search-input" id="partner_display" name="partner_display" value="<?php echo e(old('partner_display', $user->partner ? $user->partner->name : '')); ?>" placeholder="Search partner..." list="partner-list">
                            <input type="hidden" id="partner_id" name="partner_id" value="<?php echo e(old('partner_id', $user->partner_id)); ?>">
                            <i class="bi bi-search blulinc-search-icon"></i>
                        </div>
                        <datalist id="partner-list">
                            <option value="">-- None --</option>
                            <?php $__currentLoopData = $partners; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $partner): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($partner->name); ?>" data-id="<?php echo e($partner->id); ?>" <?php echo e(old('partner_id', $user->partner_id) == $partner->id ? 'selected' : ''); ?>>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </datalist>
                        <small class="blulinc-form-text">
                            <i class="bi bi-info-circle me-1"></i>Type to search for a partner
                        </small>
                        <?php $__errorArgs = ['partner_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <span class="blulinc-invalid-feedback"><?php echo e($message); ?></span>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>

                    <!-- Additional Partners Field -->
                    <div class="blulinc-form-group" id="additional-partners-container">
                        <label class="blulinc-form-label">
                            <i class="bi bi-building me-1"></i>Additional Partners
                        </label>
                        <div class="blulinc-search-container">
                            <input type="text" class="blulinc-form-control blulinc-search-input" id="additional_partners_display" name="additional_partners_display" placeholder="Search additional partners..." list="additional-partners-list">
                            <input type="hidden" id="additional_partners_ids" name="additional_partners_ids" value="<?php echo e($user->partners()->pluck('partner_id')->implode(',')); ?>">
                            <i class="bi bi-search blulinc-search-icon"></i>
                        </div>
                        <datalist id="additional-partners-list">
                            <?php $__currentLoopData = $partners; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $partner): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($partner->name); ?>" data-id="<?php echo e($partner->id); ?>">
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </datalist>
                        <div id="selected-additional-partners" class="mt-2">
                            <?php $__currentLoopData = $user->partners; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $partner): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <span class="badge bg-primary me-1 mb-1" data-id="<?php echo e($partner->id); ?>">
                                    <?php echo e($partner->name); ?> 
                                    <button type="button" class="btn-close btn-close-white ms-1" aria-label="Remove" data-id="<?php echo e($partner->id); ?>"></button>
                                </span>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </div>
                        <small class="blulinc-form-text">
                            <i class="bi bi-info-circle me-1"></i>Type to search and select additional partners
                        </small>
                        <div class="mt-2">
                            <button type="button" class="btn btn-sm btn-outline-danger" id="clear-additional-partners">
                                <i class="bi bi-trash me-1"></i>Clear All
                            </button>
                        </div>
                    </div>

                    <div class="blulinc-form-group">
                        <label for="password" class="blulinc-form-label">
                            <i class="bi bi-lock me-1"></i>Password (Leave blank to keep current password)
                        </label>
                        <div class="blulinc-password-container">
                            <input type="password" class="blulinc-form-control" id="password" name="password" placeholder="Leave blank to keep current password">
                            <button type="button" class="blulinc-password-toggle" onclick="togglePassword('password')">
                                <i class="bi bi-eye" id="password-icon"></i>
                            </button>
                        </div>
                        <small class="blulinc-form-text">
                            <i class="bi bi-info-circle me-1"></i>Leave blank to keep the current password unchanged
                        </small>
                        <?php $__errorArgs = ['password'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <span class="blulinc-invalid-feedback"><?php echo e($message); ?></span>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>
                    
                    <div class="blulinc-form-group">
                        <label for="password_confirmation" class="blulinc-form-label">
                            <i class="bi bi-lock-fill me-1"></i>Confirm Password
                        </label>
                        <div class="blulinc-password-container">
                            <input type="password" class="blulinc-form-control blulinc-password-input" id="password_confirmation" name="password_confirmation">
                            <button type="button" class="blulinc-password-toggle" onclick="togglePassword('password_confirmation')">
                                <i class="bi bi-eye" id="password_confirmation-icon"></i>
                            </button>
                        </div>
                    </div>
                    
                    <div class="blulinc-form-group">
                        <label for="role" class="blulinc-form-label">Role</label>
                        <select class="blulinc-form-select" id="role" name="role" required>
                            <option value="super-admin" <?php echo e(old('role', $user->hasRole('super-admin') ? 'super-admin' : '') == 'super-admin' ? 'selected' : ''); ?>>Super Admin</option>
                            <option value="partner-admin" <?php echo e(old('role', $user->hasRole('partner-admin') ? 'partner-admin' : '') == 'partner-admin' ? 'selected' : ''); ?>>Partner Admin</option>
                            <option value="user" <?php echo e(old('role', $user->hasRole('user') ? 'user' : '') == 'user' ? 'selected' : ''); ?>>User</option>
                        </select>
                    </div>
                    
                    <div class="blulinc-form-group">
                        <label for="is_active" class="blulinc-form-label">
                            <i class="bi bi-toggle-on me-1"></i>Status
                        </label>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="is_active" name="is_active" value="1" <?php echo e(old('is_active', $user->is_active) ? 'checked' : ''); ?>>
                            <label class="form-check-label" for="is_active">
                                Active User
                            </label>
                        </div>
                        <small class="blulinc-form-text">
                            <i class="bi bi-info-circle me-1"></i>Uncheck to deactivate this user
                        </small>
                        <?php $__errorArgs = ['is_active'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <span class="blulinc-invalid-feedback"><?php echo e($message); ?></span>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>
                    
                    <div class="button-group">
                        <button type="submit" class="blulinc-btn-primary">
                            <i class="bi bi-check-circle me-2"></i>Save Changes
                        </button>
                        <a href="<?php echo e(route('user-management.index')); ?>" class="blulinc-btn-secondary">
                            <i class="bi bi-arrow-left me-2"></i>Cancel
                        </a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const roleSelect = document.getElementById('role');
    const partnerContainer = document.getElementById('partner-field-container');
    const partnerDisplay = document.getElementById('partner_display');
    const partnerIdHidden = document.getElementById('partner_id');
    const partnerList = document.getElementById('partner-list');
    const additionalPartnersContainer = document.getElementById('additional-partners-container');
    const additionalPartnersDisplay = document.getElementById('additional_partners_display');
    const additionalPartnersIdsHidden = document.getElementById('additional_partners_ids');
    const additionalPartnersList = document.getElementById('additional-partners-list');
    const selectedAdditionalPartnersDiv = document.getElementById('selected-additional-partners');
    const clearAdditionalPartnersBtn = document.getElementById('clear-additional-partners');

    // Store all available partners initially from the datalist
    const allAvailablePartners = Array.from(additionalPartnersList.options).map(option => ({
        id: option.dataset.id,
        name: option.value
    }));

    // Initialize selected partners array based on hidden input value for edit page
    let selectedPartners = [];
    if (additionalPartnersIdsHidden.value) {
        const initialIds = additionalPartnersIdsHidden.value.split(',').filter(id => id);
        selectedPartners = allAvailablePartners.filter(p => initialIds.includes(p.id));
        console.log('Initial selected partners:', selectedPartners);
    }

    // Function to update the display of selected partners and the datalist
    function updateSelectedPartnersDisplay() {
        // Update hidden input
        additionalPartnersIdsHidden.value = selectedPartners.map(p => p.id).join(',');
        console.log('Updated hidden input value:', additionalPartnersIdsHidden.value);

        // Render badges with remove buttons
        selectedAdditionalPartnersDiv.innerHTML = selectedPartners.map(p => `
            <span class="badge bg-primary me-1 mb-1" data-id="${p.id}">
                ${p.name} 
                <button type="button" class="btn-close btn-close-white ms-1" aria-label="Remove" data-id="${p.id}"></button>
            </span>
        `).join('');

        // Re-populate datalist with unselected partners only
        additionalPartnersList.innerHTML = '';
        const unselectedPartners = allAvailablePartners.filter(p => 
            !selectedPartners.some(sp => sp.id === p.id)
        );
        
        unselectedPartners.forEach(p => {
            const option = document.createElement('option');
            option.value = p.name;
            option.dataset.id = p.id;
            additionalPartnersList.appendChild(option);
        });

        // Clear the display input
        additionalPartnersDisplay.value = '';
        console.log('Updated datalist with', unselectedPartners.length, 'unselected partners');
    }

    // Event listener for selecting a partner from the datalist
    additionalPartnersDisplay.addEventListener('input', function() {
        const selectedOption = additionalPartnersList.querySelector(`option[value="${this.value}"]`);
        if (selectedOption) {
            const partnerId = selectedOption.dataset.id;
            const partnerName = selectedOption.value;

            // Add only if not already selected
            if (!selectedPartners.some(p => p.id === partnerId)) {
                selectedPartners.push({ id: partnerId, name: partnerName });
                console.log('Added partner:', partnerName, 'ID:', partnerId);
                updateSelectedPartnersDisplay();
            } else {
                console.log('Partner already selected:', partnerName);
            }
        }
    });

    // Event listener for removing individual partners (delegated)
    selectedAdditionalPartnersDiv.addEventListener('click', function(event) {
        if (event.target.classList.contains('btn-close')) {
            const partnerIdToRemove = event.target.dataset.id;
            const partnerToRemove = selectedPartners.find(p => p.id === partnerIdToRemove);
            selectedPartners = selectedPartners.filter(p => p.id !== partnerIdToRemove);
            console.log('Removed partner:', partnerToRemove?.name, 'ID:', partnerIdToRemove);
            updateSelectedPartnersDisplay();
        }
    });

    // Event listener for "Clear All" button
    if (clearAdditionalPartnersBtn) {
        clearAdditionalPartnersBtn.addEventListener('click', function() {
            if (confirm('Are you sure you want to clear all additional partners?')) {
                selectedPartners = [];
                console.log('Cleared all partners');
                updateSelectedPartnersDisplay();
            }
        });
    }

    // Initial display update on page load
    updateSelectedPartnersDisplay();

    function toggleFields() {
        if (roleSelect.value === 'partner-admin') {
            partnerContainer.style.display = 'block';
            partnerDisplay.required = true;
            additionalPartnersContainer.style.display = 'block';
            additionalPartnersDisplay.required = false; // No requerir el campo de búsqueda
            additionalPartnersIdsHidden.required = false; // No requerir el campo hidden
        } else {
            partnerContainer.style.display = 'none';
            partnerDisplay.required = false;
            partnerDisplay.value = '';
            partnerIdHidden.value = '';
            additionalPartnersContainer.style.display = 'none';
            additionalPartnersDisplay.value = '';
            additionalPartnersIdsHidden.value = '';
            selectedPartners = [];
            updateSelectedPartnersDisplay();
        }
    }

    roleSelect.addEventListener('change', toggleFields);
    
    // Initialize on page load
    toggleFields();

    // Función para encontrar el ID del partner por nombre
    function findPartnerIdByName(partnerName) {
        const options = partnerList.querySelectorAll('option');
        for (let option of options) {
            if (option.value === partnerName) {
                return option.getAttribute('data-id');
            }
        }
        return null;
    }

    // Handle partner datalist selection
    if (partnerDisplay && partnerList) {
        // Evento input para cuando el usuario escribe
        partnerDisplay.addEventListener('input', function() {
            const partnerName = this.value.trim();
            const partnerId = findPartnerIdByName(partnerName);
            
            if (partnerId) {
                partnerIdHidden.value = partnerId;
                console.log('Partner found:', partnerName, 'ID:', partnerId);
            } else {
                partnerIdHidden.value = '';
                console.log('Partner not found:', partnerName);
            }
        });

        // Evento change para cuando el usuario selecciona del datalist
        partnerDisplay.addEventListener('change', function() {
            const partnerName = this.value.trim();
            const partnerId = findPartnerIdByName(partnerName);
            
            if (partnerId) {
                partnerIdHidden.value = partnerId;
                console.log('Partner selected:', partnerName, 'ID:', partnerId);
            } else {
                partnerIdHidden.value = '';
                console.log('Partner not found:', partnerName);
            }
        });

        // Evento blur para cuando el usuario termina de escribir
        partnerDisplay.addEventListener('blur', function() {
            const partnerName = this.value.trim();
            const partnerId = findPartnerIdByName(partnerName);
            
            if (partnerId) {
                partnerIdHidden.value = partnerId;
                console.log('Partner confirmed:', partnerName, 'ID:', partnerId);
            } else {
                partnerIdHidden.value = '';
                console.log('Partner not found:', partnerName);
            }
        });
    }

    // Before form submission, validate partner selection
    document.querySelector('form').addEventListener('submit', function(e) {
        const partnerId = partnerIdHidden.value;
        const partnerName = partnerDisplay.value.trim();
        
        console.log('Form submission - Partner name:', partnerName, 'Partner ID:', partnerId);
        console.log('Additional partners before submit:', selectedPartners);
        console.log('Additional partners IDs:', additionalPartnersIdsHidden.value);
        
        if (roleSelect.value === 'partner-admin') {
            if (partnerId && partnerName) {
                console.log('Partner ID set to:', partnerId);
            } else {
                // Si es partner-admin pero no hay partner válido, prevenir envío
                e.preventDefault();
                alert('Please select a valid partner for Partner Admin role.');
                return false;
            }
        } else {
            // Para otros roles, limpiar el partner_id
            partnerIdHidden.value = '';
        }

        // Validate additional partners - make it optional
        const additionalPartnerIds = additionalPartnersIdsHidden.value.split(',').filter(id => id);
        if (roleSelect.value === 'partner-admin' && additionalPartnerIds.length === 0) {
            // Opcional: mostrar advertencia pero permitir continuar
            if (!confirm('No additional partners selected. Do you want to continue?')) {
                e.preventDefault();
                return false;
            }
        }
    });
});

// Función para mostrar/ocultar contraseña
function togglePassword(inputId) {
    const input = document.getElementById(inputId);
    const icon = document.getElementById(inputId + '-icon');
    
    if (input.type === 'password') {
        input.type = 'text';
        icon.classList.remove('bi-eye');
        icon.classList.add('bi-eye-slash');
    } else {
        input.type = 'password';
        icon.classList.remove('bi-eye-slash');
        icon.classList.add('bi-eye');
    }
}
</script>
<?php $__env->stopSection(); ?> 
<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /home/pixjucom/blulinc.pixju.com/resources/views/users/edit.blade.php ENDPATH**/ ?>