

<?php $__env->startSection('title', 'แก้ไขผู้ใช้ - ระบบจัดการค่าคอมมิชชั่น'); ?>

<?php $__env->startSection('content'); ?>
<div class="content-container">
    <!-- Page Header -->
    <div class="page-header">
        <div class="flex items-center justify-between">
            <div>
                <h1 class="page-title">แก้ไขผู้ใช้</h1>
                <p class="page-subtitle">แก้ไขข้อมูล: <?php echo e($user->name ?? ''); ?></p>
            </div>
            <a href="<?php echo e(route('admin.users.index')); ?>" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i>กลับไปรายการ
            </a>
        </div>
    </div>

    <!-- Form Container -->
    <div class="table-container">
        <div class="table-header">
            <h3 class="table-title">ข้อมูลผู้ใช้</h3>
        </div>
        
        <div class="p-6">
            <form method="POST" action="<?php echo e(route('admin.users.update', $user)); ?>" id="userForm">
                <?php echo csrf_field(); ?>
                <?php echo method_field('PUT'); ?>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <!-- ชื่อ -->
                    <div class="form-group">
                        <label for="first_name" class="form-label">ชื่อ <span class="text-red-500">*</span></label>
                        <input type="text" id="first_name" name="first_name" 
                               value="<?php echo e(old('first_name', $user->first_name ?? '')); ?>" 
                               class="form-control <?php $__errorArgs = ['first_name'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> border-red-500 <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" required>
                        <?php $__errorArgs = ['first_name'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <p class="mt-1 text-sm text-red-600"><?php echo e($message); ?></p>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>

                    <!-- นามสกุล -->
                    <div class="form-group">
                        <label for="last_name" class="form-label">นามสกุล <span class="text-red-500">*</span></label>
                        <input type="text" id="last_name" name="last_name" 
                               value="<?php echo e(old('last_name', $user->last_name ?? '')); ?>" 
                               class="form-control <?php $__errorArgs = ['last_name'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> border-red-500 <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" required>
                        <?php $__errorArgs = ['last_name'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <p class="mt-1 text-sm text-red-600"><?php echo e($message); ?></p>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>

                    <!-- อีเมล -->
                    <div class="form-group">
                        <label for="email" class="form-label">อีเมล <span class="text-red-500">*</span></label>
                        <input type="email" id="email" name="email" 
                               value="<?php echo e(old('email', $user->email ?? '')); ?>" 
                               class="form-control <?php $__errorArgs = ['email'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> border-red-500 <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" required>
                        <?php $__errorArgs = ['email'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <p class="mt-1 text-sm text-red-600"><?php echo e($message); ?></p>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>

                    <!-- รหัสผ่านใหม่ (ไม่บังคับ) -->
                    <div class="form-group">
                        <label for="password" class="form-label">รหัสผ่านใหม่ (ถ้าต้องการเปลี่ยน)</label>
                        <div class="relative">
                            <input type="password" id="password" name="password" 
                                   class="form-control <?php $__errorArgs = ['password'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> border-red-500 <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>">
                            <button type="button" onclick="togglePassword('password')" 
                                    class="absolute inset-y-0 right-0 pr-3 flex items-center">
                                <i class="fas fa-eye text-gray-400" id="password-icon"></i>
                            </button>
                        </div>
                        <?php $__errorArgs = ['password'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <p class="mt-1 text-sm text-red-600"><?php echo e($message); ?></p>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                        <p class="mt-1 text-sm text-gray-500">เว้นว่างไว้หากไม่ต้องการเปลี่ยนรหัสผ่าน</p>
                    </div>

                    <!-- ยืนยันรหัสผ่าน -->
                    <div class="form-group">
                        <label for="password_confirmation" class="form-label">ยืนยันรหัสผ่านใหม่</label>
                        <div class="relative">
                            <input type="password" id="password_confirmation" name="password_confirmation" 
                                   class="form-control">
                            <button type="button" onclick="togglePassword('password_confirmation')" 
                                    class="absolute inset-y-0 right-0 pr-3 flex items-center">
                                <i class="fas fa-eye text-gray-400" id="password_confirmation-icon"></i>
                            </button>
                        </div>
                    </div>

                    <!-- บทบาท -->
                    <div class="form-group">
                        <label for="role" class="form-label">บทบาท <span class="text-red-500">*</span></label>
                        <select id="role" name="role" class="form-control <?php $__errorArgs = ['role'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> border-red-500 <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" required>
                            <option value="">เลือกบทบาท</option>
                            <option value="admin" <?php echo e(old('role', $user->role ?? '') === 'admin' ? 'selected' : ''); ?>>ผู้ดูแลระบบ</option>
                            <option value="2wheel" <?php echo e(old('role', $user->role ?? '') === '2wheel' ? 'selected' : ''); ?>>รถ 2 ล้อ</option>
                            <option value="4wheel" <?php echo e(old('role', $user->role ?? '') === '4wheel' ? 'selected' : ''); ?>>รถ 4 ล้อ</option>
                        </select>
                        <?php $__errorArgs = ['role'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <p class="mt-1 text-sm text-red-600"><?php echo e($message); ?></p>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                        <?php if($user->id === auth()->id()): ?>
                            <p class="mt-1 text-sm text-yellow-600">
                                <i class="fas fa-exclamation-triangle"></i> คุณไม่สามารถเปลี่ยนบทบาทของตัวเองได้
                            </p>
                        <?php endif; ?>
                    </div>

                    <!-- คลังสินค้า -->
                    <div class="form-group" id="warehouse-group">
                        <label for="warehouse_code" class="form-label">คลังสินค้า <span class="text-red-500">*</span></label>
                        <select id="warehouse_code" name="warehouse_code" class="form-control <?php $__errorArgs = ['warehouse_code'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> border-red-500 <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>">
                            <option value="">เลือกคลังสินค้า</option>
                            <?php $__currentLoopData = $warehouses ?? []; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $warehouse): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($warehouse->code); ?>" 
                                        <?php echo e(old('warehouse_code', $user->warehouse_code ?? '') === $warehouse->code ? 'selected' : ''); ?>>
                                    <?php echo e($warehouse->code); ?> - <?php echo e($warehouse->name); ?>

                                </option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                        <?php $__errorArgs = ['warehouse_code'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <p class="mt-1 text-sm text-red-600"><?php echo e($message); ?></p>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>

                    <!-- สถานะ -->
                    <div class="form-group">
                        <label for="is_active" class="form-label">สถานะ</label>
                        <div class="flex items-center space-x-3">
                            <label class="flex items-center">
                                <input type="radio" name="is_active" value="1" 
                                       <?php echo e(old('is_active', $user->is_active ?? true) ? 'checked' : ''); ?>

                                       class="text-orange-600 focus:ring-orange-500"
                                       <?php echo e($user->id === auth()->id() ? 'disabled' : ''); ?>>
                                <span class="ml-2">ใช้งานอยู่</span>
                            </label>
                            <label class="flex items-center">
                                <input type="radio" name="is_active" value="0" 
                                       <?php echo e(!old('is_active', $user->is_active ?? true) ? 'checked' : ''); ?>

                                       class="text-orange-600 focus:ring-orange-500"
                                       <?php echo e($user->id === auth()->id() ? 'disabled' : ''); ?>>
                                <span class="ml-2">ปิดใช้งาน</span>
                            </label>
                        </div>
                        <?php if($user->id === auth()->id()): ?>
                            <p class="mt-1 text-sm text-yellow-600">
                                <i class="fas fa-exclamation-triangle"></i> คุณไม่สามารถปิดการใช้งานตัวเองได้
                            </p>
                        <?php endif; ?>
                    </div>

                    <!-- ข้อมูลเพิ่มเติม -->
                    <div class="form-group">
                        <label class="form-label">สร้างเมื่อ</label>
                        <div class="p-3 bg-gray-50 rounded-lg text-gray-700">
                            <?php echo e($user->created_at ? $user->created_at->format('d/m/Y H:i:s') : '-'); ?>

                        </div>
                    </div>

                    <div class="form-group">
                        <label class="form-label">อัปเดตล่าสุด</label>
                        <div class="p-3 bg-gray-50 rounded-lg text-gray-700">
                            <?php echo e($user->updated_at ? $user->updated_at->format('d/m/Y H:i:s') : '-'); ?>

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

                <!-- Submit Buttons -->
                <div class="flex justify-between items-center mt-8 pt-6 border-t border-gray-200">
                    <div class="flex space-x-3">
                        <?php if($user->id !== auth()->id()): ?>
                        <button type="button" onclick="resetPassword()" class="btn btn-warning">
                            <i class="fas fa-key"></i>รีเซ็ตรหัสผ่าน
                        </button>
                        <button type="button" onclick="deleteUser()" class="btn btn-danger">
                            <i class="fas fa-trash"></i>ลบผู้ใช้
                        </button>
                        <?php endif; ?>
                    </div>
                    
                    <div class="flex space-x-3">
                        <a href="<?php echo e(route('admin.users.index')); ?>" class="btn btn-secondary">
                            <i class="fas fa-times"></i>ยกเลิก
                        </a>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i>บันทึกการเปลี่ยนแปลง
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
// Show/hide warehouse field based on role
document.getElementById('role').addEventListener('change', function() {
    const warehouseGroup = document.getElementById('warehouse-group');
    const warehouseSelect = document.getElementById('warehouse_code');
    
    if (this.value === '2wheel' || this.value === '4wheel') {
        warehouseGroup.style.display = 'block';
        warehouseSelect.required = true;
    } else {
        warehouseGroup.style.display = 'none';
        warehouseSelect.required = false;
        warehouseSelect.value = '';
    }
});

// Trigger on page load
document.addEventListener('DOMContentLoaded', function() {
    const roleSelect = document.getElementById('role');
    if (roleSelect.value) {
        roleSelect.dispatchEvent(new Event('change'));
    }
    
    // Disable role change for current user
    <?php if($user->id === auth()->id()): ?>
    roleSelect.disabled = true;
    <?php endif; ?>
});

// Toggle password visibility
function togglePassword(fieldId) {
    const field = document.getElementById(fieldId);
    const icon = document.getElementById(fieldId + '-icon');
    
    if (field.type === 'password') {
        field.type = 'text';
        icon.classList.remove('fa-eye');
        icon.classList.add('fa-eye-slash');
    } else {
        field.type = 'password';
        icon.classList.remove('fa-eye-slash');
        icon.classList.add('fa-eye');
    }
}

// Form validation
document.getElementById('userForm').addEventListener('submit', function(e) {
    const password = document.getElementById('password').value;
    const confirmPassword = document.getElementById('password_confirmation').value;
    
    if (password && password !== confirmPassword) {
        e.preventDefault();
        Swal.fire('ข้อผิดพลาด', 'รหัสผ่านและการยืนยันรหัสผ่านไม่ตรงกัน', 'error');
        return false;
    }
    
    if (password && password.length < 8) {
        e.preventDefault();
        Swal.fire('ข้อผิดพลาด', 'รหัสผ่านต้องมีอย่างน้อย 8 ตัวอักษร', 'error');
        return false;
    }
});

// Real-time password confirmation check
document.getElementById('password_confirmation').addEventListener('input', function() {
    const password = document.getElementById('password').value;
    const confirmPassword = this.value;
    
    if (password && confirmPassword && password !== confirmPassword) {
        this.classList.add('border-red-500');
        this.classList.remove('border-gray-300');
    } else {
        this.classList.remove('border-red-500');
        this.classList.add('border-gray-300');
    }
});

// Reset password function
function resetPassword() {
    Swal.fire({
        title: 'ยืนยันการรีเซ็ตรหัสผ่าน',
        text: 'คุณต้องการรีเซ็ตรหัสผ่านของผู้ใช้นี้หรือไม่?',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#FF6B35',
        cancelButtonColor: '#6B7280',
        confirmButtonText: 'ยืนยัน',
        cancelButtonText: 'ยกเลิก'
    }).then((result) => {
        if (result.isConfirmed) {
            fetch(`<?php echo e(route('admin.users.reset-password', $user)); ?>`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    Swal.fire('สำเร็จ!', `รหัสผ่านใหม่: ${data.new_password}`, 'success');
                } else {
                    Swal.fire('เกิดข้อผิดพลาด!', data.message, 'error');
                }
            })
            .catch(error => {
                Swal.fire('เกิดข้อผิดพลาด!', 'ไม่สามารถรีเซ็ตรหัสผ่านได้', 'error');
            });
        }
    });
}

// Delete user function
function deleteUser() {
    Swal.fire({
        title: 'ยืนยันการลบ',
        text: 'คุณต้องการลบผู้ใช้นี้หรือไม่? การดำเนินการนี้ไม่สามารถยกเลิกได้',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#EF4444',
        cancelButtonColor: '#6B7280',
        confirmButtonText: 'ลบ',
        cancelButtonText: 'ยกเลิก'
    }).then((result) => {
        if (result.isConfirmed) {
            fetch(`<?php echo e(route('admin.users.destroy', $user)); ?>`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    Swal.fire('สำเร็จ!', data.message, 'success').then(() => {
                        window.location.href = '<?php echo e(route('admin.users.index')); ?>';
                    });
                } else {
                    Swal.fire('เกิดข้อผิดพลาด!', data.message, 'error');
                }
            })
            .catch(error => {
                Swal.fire('เกิดข้อผิดพลาด!', 'ไม่สามารถลบผู้ใช้ได้', 'error');
            });
        }
    });
}
</script>

<style>
.btn-secondary {
    background: #6B7280;
    color: white;
}
.btn-secondary:hover {
    background: #4B5563;
}
.btn-warning {
    background: #F59E0B;
    color: white;
}
.btn-warning:hover {
    background: #D97706;
}
.btn-danger {
    background: #EF4444;
    color: white;
}
.btn-danger:hover {
    background: #DC2626;
}
</style>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /home/zlerpszw/public_html/www.crs.niendsitekungz.com/resources/views/admin/users/edit.blade.php ENDPATH**/ ?>