<div class="main">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="fd-3 mb-0">My Profile</h2>
        <button class="btn btn-primary btn-sm" onclick="toggleEditMode()">
            <i class="fas fa-edit"></i> Edit Profile
        </button>
    </div>

    <div class="row g-4">
        <!-- Profile Header Card -->
        <div class="col-md-12">
            <div class="card profile-header-card">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col-md-3 text-center">
                            <div class="profile-image-container">
                                <img src="<?php echo !empty($user['image']) ? $user['image'] : base_url('assets/images/default-avatar.png'); ?>" 
                                     alt="Profile Picture" class="profile-image">
                                <div class="online-status <?php echo ($user['isOnline'] == 1) ? 'online' : 'offline'; ?>"></div>
                            </div>
                            <button class="btn btn-outline-primary btn-sm mt-2" onclick="changeProfilePicture()">
                                Change Photo
                            </button>
                        </div>
                        <div class="col-md-9">
                            <div class="profile-info">
                                <h3 class="mb-2"><?php echo !empty($user['userName']) ? $user['userName'] : 'User Name'; ?></h3>
                                <p class="text-muted mb-2">
                                    <i class="fas fa-envelope"></i> <?php echo !empty($user['email']) ? $user['email'] : 'No email provided'; ?>
                                </p>
                                <p class="text-muted mb-2">
                                    <i class="fas fa-user-tag"></i> <?php echo ucfirst($user['userRole']); ?>
                                </p>
                                <p class="text-muted mb-0">
                                    <i class="fas fa-calendar-alt"></i> Member since <?php echo date('F Y', $user['userDate'] / 1000); ?>
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Account Balance Card -->
        <div class="col-md-4 d-none">
            <div class="card balance-card">
                <div class="card-body text-center">
                    <div class="balance-icon">
                        <i class="fas fa-wallet"></i>
                    </div>
                    <h4 class="balance-amount">$<?php echo number_format($user['balance'], 2); ?></h4>
                    <p class="text-muted mb-3">Account Balance</p>
                    <button class="btn btn-success btn-sm">Add Funds</button>
                </div>
            </div>
        </div>

        <!-- Rating Card -->
        <div class="col-md-4 d-none">
            <div class="card rating-card">
                <div class="card-body text-center">
                    <div class="rating-icon">
                        <i class="fas fa-star"></i>
                    </div>
                    <h4 class="rating-score"><?php echo number_format($user['avgRating'], 1); ?></h4>
                    <p class="text-muted mb-1">Average Rating</p>
                    <small class="text-muted">Based on <?php echo $user['totalRating']; ?> reviews</small>
                </div>
            </div>
        </div>

        <!-- Device Info Card -->
        <div class="col-md-4 d-none" >
            <div class="card device-card">
                <div class="card-body text-center">
                    <div class="device-icon">
                        <i class="fas fa-<?php echo strtolower($user['deviceType']) === 'ios' ? 'mobile-alt' : 'android'; ?>"></i>
                    </div>
                    <h5 class="device-type"><?php echo $user['deviceType']; ?></h5>
                    <p class="text-muted mb-1">Device Type</p>
                    <small class="text-muted">
                        Status: <?php echo ($user['isActive'] == 1) ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-secondary">Inactive</span>'; ?>
                    </small>
                </div>
            </div>
        </div>

        <!-- Personal Information Card -->
        <div class="col-md-8">
            <div class="card info-card">
                <div class="card-header">
                    <h5 class="mb-0">Personal Information</h5>
                </div>
                <div class="card-body">
                    <form id="profileForm">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label for="firstName" class="form-label">First Name</label>
                                <input type="text" class="form-control" id="firstName" name="firstName" 
                                       value="<?php echo !empty($user['firstName']) ? $user['firstName'] : ''; ?>" readonly>
                            </div>
                            <div class="col-md-6">
                                <label for="userName" class="form-label">User Name</label>
                                <input type="text" class="form-control" id="userName" name="userName" 
                                       value="<?php echo !empty($user['userName']) ? $user['userName'] : ''; ?>" readonly>
                            </div>
                            <div class="col-md-12">
                                <label for="email" class="form-label">Email Address</label>
                                <input type="email" class="form-control" id="email" name="email" 
                                       value="<?php echo !empty($user['email']) ? $user['email'] : ''; ?>" readonly>
                            </div>
                            <div class="col-md-6">
                                <label for="userRole" class="form-label">User Role</label>
                                <input type="text" class="form-control" id="userRole" name="userRole" 
                                       value="<?php echo ucfirst($user['userRole']); ?>" readonly>
                            </div>
                            <div class="col-md-6">
                                <label for="memberSince" class="form-label">Member Since</label>
                                <input type="text" class="form-control" id="memberSince" name="memberSince" 
                                       value="<?php echo date('F j, Y', $user['userDate'] / 1000); ?>" readonly>
                            </div>
                        </div>
                        
                        <div class="mt-4 edit-buttons" style="display: none;">
                            <button type="button" class="btn btn-success" onclick="saveProfile()">Save Changes</button>
                            <button type="button" class="btn btn-secondary" onclick="cancelEdit()">Cancel</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Account Details Card -->
        <div class="col-md-4">
            <div class="card account-card">
                <div class="card-header">
                    <h5 class="mb-0">Account Details</h5>
                </div>
                <div class="card-body">
                    <div class="account-detail">
                        <label>User ID:</label>
                        <span class="detail-value"><?php echo $user['id']; ?></span>
                        <button class="btn btn-sm btn-outline-secondary copy-btn" onclick="copyToClipboard('<?php echo $user['id']; ?>')">
                            <i class="fas fa-copy"></i>
                        </button>
                    </div>
                    
                    <?php if(!empty($user['stripeCustid'])): ?>
                    <div class="account-detail">
                        <label>Stripe Customer ID:</label>
                        <span class="detail-value"><?php echo $user['stripeCustid']; ?></span>
                        <button class="btn btn-sm btn-outline-secondary copy-btn" onclick="copyToClipboard('<?php echo $user['stripeCustid']; ?>')">
                            <i class="fas fa-copy"></i>
                        </button>
                    </div>
                    <?php endif; ?>
                    
                    <div class="account-detail">
                        <label>Last Session:</label>
                        <span class="detail-value"><?php echo date('M j, Y g:i A', $user['sessionTime'] / 1000); ?></span>
                    </div>
                    
                    <div class="account-detail">
                        <label>Device Type:</label>
                        <span class="detail-value">
                            <span class="badge bg-<?php echo strtolower($user['deviceType']) === 'ios' ? 'primary' : 'success'; ?>">
                                <?php echo $user['deviceType']; ?>
                            </span>
                        </span>
                    </div>
                    
                    <div class="account-detail">
                        <label>Account Status:</label>
                        <span class="detail-value">
                            <?php if($user['isActive'] == 1): ?>
                                <span class="badge bg-success">Active</span>
                            <?php else: ?>
                                <span class="badge bg-secondary">Inactive</span>
                            <?php endif; ?>
                        </span>
                    </div>
                    
                    <hr class="my-3">
                    
                    <!-- Security Section -->
                    <div class="security-section">
                        <h6 class="mb-3">
                            <i class="fas fa-shield-alt text-primary"></i> Security Settings
                        </h6>
                        
                        <div class="d-grid gap-2">
                            <a href="<?php echo base_url('dashboard/changepassword'); ?>" class="btn btn-outline-primary btn-sm">
                                <i class="fas fa-key"></i> Change Password
                            </a>
                            
                          
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Statistics Card -->
        <div class="col-md-12 d-none">
            <div class="card stats-card">
                <div class="card-header">
                    <h5 class="mb-0">Account Statistics</h5>
                </div>
                <div class="card-body">
                    <div class="row text-center">
                        <div class="col-md-3">
                            <div class="stat-item">
                                <div class="stat-icon">
                                    <i class="fas fa-star text-warning"></i>
                                </div>
                                <h4><?php echo number_format($user['avgRating'], 1); ?></h4>
                                <p class="text-muted">Average Rating</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stat-item">
                                <div class="stat-icon">
                                    <i class="fas fa-comments text-info"></i>
                                </div>
                                <h4><?php echo $user['totalRating']; ?></h4>
                                <p class="text-muted">Total Reviews</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stat-item">
                                <div class="stat-icon">
                                    <i class="fas fa-wallet text-success"></i>
                                </div>
                                <h4>$<?php echo number_format($user['balance'], 2); ?></h4>
                                <p class="text-muted">Current Balance</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stat-item">
                                <div class="stat-icon">
                                    <i class="fas fa-clock text-primary"></i>
                                </div>
                                <h4><?php echo ($user['isOnline'] == 1) ? 'Online' : 'Offline'; ?></h4>
                                <p class="text-muted">Current Status</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>


<style>
/* Profile Header Card */
.profile-header-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border: none;
    border-radius: 15px;
    overflow: hidden;
}

.profile-image-container {
    position: relative;
    display: inline-block;
}

.profile-image {
    width: 120px;
    height: 120px;
    border-radius: 50%;
    border: 4px solid white;
    object-fit: cover;
    box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}

.online-status {
    position: absolute;
    bottom: 10px;
    right: 10px;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    border: 3px solid white;
}

.online-status.online {
    background-color: #28a745;
    animation: pulse 2s infinite;
}

.online-status.offline {
    background-color: #6c757d;
}

@keyframes pulse {
    0% {
        box-shadow: 0 0 0 0 rgba(40, 167, 69, 0.7);
    }
    70% {
        box-shadow: 0 0 0 10px rgba(40, 167, 69, 0);
    }
    100% {
        box-shadow: 0 0 0 0 rgba(40, 167, 69, 0);
    }
}

.profile-info h3 {
    color: white;
    font-weight: 600;
}

.profile-info p {
    color: rgba(255,255,255,0.8);
    margin-bottom: 8px;
}

.profile-info i {
    margin-right: 8px;
    width: 16px;
}

/* Balance Card */
.balance-card {
    background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
    color: white;
    border: none;
    border-radius: 15px;
}

.balance-icon {
    font-size: 2.5rem;
    margin-bottom: 15px;
    opacity: 0.8;
}

.balance-amount {
    font-size: 2.5rem;
    font-weight: 700;
    margin-bottom: 10px;
}

/* Rating Card */
.rating-card {
    background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
    border: none;
    border-radius: 15px;
}

.rating-icon {
    font-size: 2.5rem;
    color: #ffc107;
    margin-bottom: 15px;
}

.rating-score {
    font-size: 2.5rem;
    font-weight: 700;
    color: #856404;
    margin-bottom: 10px;
}

/* Device Card */
.device-card {
    background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
    border: none;
    border-radius: 15px;
}

.device-icon {
    font-size: 2.5rem;
    color: #495057;
    margin-bottom: 15px;
}

.device-type {
    font-weight: 600;
    color: #495057;
    margin-bottom: 10px;
}

/* Information Card */
.info-card {
    border-radius: 15px;
    border: none;
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}

.info-card .card-header {
    background: #f8f9fa;
    border-bottom: 2px solid #e9ecef;
    border-radius: 15px 15px 0 0 !important;
}

/* Account Details Card */
.account-card {
    border-radius: 15px;
    border: none;
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}

.account-card .card-header {
    background: #f8f9fa;
    border-bottom: 2px solid #e9ecef;
    border-radius: 15px 15px 0 0 !important;
}

.account-detail {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f0f0f0;
}

.account-detail:last-child {
    border-bottom: none;
}

.account-detail label {
    font-weight: 600;
    color: #495057;
    margin: 0;
    flex: 1;
}

.detail-value {
    flex: 2;
    font-family: monospace;
    font-size: 0.9rem;
    color: #6c757d;
    word-break: break-all;
}

.copy-btn {
    margin-left: 8px;
    padding: 2px 6px;
}

/* Statistics Card */
.stats-card {
    border-radius: 15px;
    border: none;
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}

.stats-card .card-header {
    background: #f8f9fa;
    border-bottom: 2px solid #e9ecef;
    border-radius: 15px 15px 0 0 !important;
}

.stat-item {
    padding: 20px;
    border-radius: 10px;
    background: #f8f9fa;
    margin: 0 10px;
    transition: transform 0.3s ease;
}

.stat-item:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 25px rgba(0,0,0,0.1);
}

.stat-icon {
    font-size: 2rem;
    margin-bottom: 10px;
}

.stat-item h4 {
    font-weight: 700;
    margin-bottom: 5px;
    color: #495057;
}

.stat-item p {
    margin: 0;
    font-size: 0.9rem;
}

/* Form styling */
.form-control:read-only {
    background-color: #f8f9fa;
    opacity: 1;
}

.form-control.editable {
    background-color: white;
    border-color: #007bff;
}

.edit-buttons {
    text-align: center;
    padding-top: 20px;
    border-top: 1px solid #e9ecef;
}

/* Responsive design */
@media (max-width: 768px) {
    .profile-image {
        width: 100px;
        height: 100px;
    }
    
    .balance-amount, .rating-score {
        font-size: 2rem;
    }
    
    .stat-item {
        margin: 10px 0;
        padding: 15px;
    }
    
    .account-detail {
        flex-direction: column;
        align-items: flex-start;
        gap: 5px;
    }
    
    .detail-value {
        font-size: 0.8rem;
    }
}

/* Animation for cards */
.card {
    transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.card:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0,0,0,0.15);
}

/* Badge styling */
.badge {
    font-size: 0.75rem;
    padding: 0.375rem 0.75rem;
}

/* Profile upload styling */
.profile-upload {
    text-align: center;
    padding: 20px;
}

.upload-area {
    border: 2px dashed #007bff;
    border-radius: 10px;
    padding: 40px 20px;
    cursor: pointer;
    transition: all 0.3s ease;
    background: #f8f9fa;
}

.upload-area:hover {
    border-color: #0056b3;
    background: #e3f2fd;
}

.upload-area.drag-over {
    border-color: #28a745;
    background: #e8f5e8;
    transform: scale(1.02);
}

.upload-content {
    pointer-events: none;
}

.upload-icon {
    font-size: 3rem;
    color: #007bff;
    margin-bottom: 15px;
}

.upload-area p {
    color: #495057;
    font-weight: 500;
    margin-bottom: 5px;
}

.upload-area small {
    color: #6c757d;
    font-size: 0.8rem;
}

.image-preview {
    position: relative;
    display: inline-block;
    border-radius: 10px;
    overflow: hidden;
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}

.image-preview img {
    max-width: 200px;
    max-height: 200px;
    object-fit: cover;
    border-radius: 10px;
}

.remove-preview {
    position: absolute;
    top: 10px;
    right: 10px;
    border-radius: 50%;
    width: 30px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0;
}

/* Upload progress styling */
.upload-progress {
    text-align: center;
    padding: 20px;
}

.upload-progress .spinner-border {
    width: 3rem;
    height: 3rem;
    border-width: 0.3em;
}

.upload-progress p {
    color: #6c757d;
    font-size: 16px;
    margin: 15px 0 5px 0;
    font-weight: 500;
}

.progress {
    height: 8px;
    border-radius: 10px;
    background-color: #e9ecef;
}

.progress-bar {
    border-radius: 10px;
    background: linear-gradient(90deg, #007bff, #28a745);
}

/* Profile upload popup */
.profile-upload-popup {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.profile-upload-popup .swal2-html-container {
    padding: 0 !important;
    margin: 0 !important;
}

/* Mobile responsive for upload */
@media (max-width: 768px) {
    .upload-area {
        padding: 30px 15px;
    }
    
    .upload-icon {
        font-size: 2.5rem;
    }
    
    .image-preview img {
        max-width: 150px;
        max-height: 150px;
    }
    
    .profile-upload-popup {
        width: 95% !important;
        max-width: none !important;
    }
}
</style>

<script>
let isEditMode = false;

function toggleEditMode() {
    isEditMode = !isEditMode;
    const form = document.getElementById('profileForm');
    const editButtons = document.querySelector('.edit-buttons');
    const toggleBtn = document.querySelector('button[onclick="toggleEditMode()"]');
    
    const editableFields = ['firstName', 'userName'];
    
    editableFields.forEach(fieldId => {
        const field = document.getElementById(fieldId);
        if (field) {
            if (isEditMode) {
                field.removeAttribute('readonly');
                field.classList.add('editable');
            } else {
                field.setAttribute('readonly', true);
                field.classList.remove('editable');
            }
        }
    });
    
    if (isEditMode) {
        editButtons.style.display = 'block';
        toggleBtn.innerHTML = '<i class="fas fa-times"></i> Cancel Edit';
        toggleBtn.className = 'btn btn-secondary btn-sm';
    } else {
        editButtons.style.display = 'none';
        toggleBtn.innerHTML = '<i class="fas fa-edit"></i> Edit Profile';
        toggleBtn.className = 'btn btn-primary btn-sm';
    }
}

function saveProfile() {
    const formData = new FormData(document.getElementById('profileForm'));
    
    // Show loading
    Swal.fire({
        title: 'Updating Profile',
        html: `
            <div class="text-center">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
                <p style="margin-top: 15px;">Saving your profile changes...</p>
            </div>
        `,
        allowOutsideClick: false,
        showConfirmButton: false
    });
    
    // Send update request
    fetch('<?php echo base_url('dashboard/update_profile'); ?>', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            Swal.fire({
                icon: 'success',
                title: 'Profile Updated!',
                text: 'Your profile has been updated successfully.',
                timer: 2000,
                timerProgressBar: true,
                showConfirmButton: false
            }).then(() => {
                location.reload(); // Refresh to show updated data
            });
        } else {
            Swal.fire({
                icon: 'error',
                title: 'Update Failed',
                text: data.message || 'Failed to update profile.',
                confirmButtonColor: '#dc3545'
            });
        }
    })
    .catch(error => {
        console.error('Error:', error);
        Swal.fire({
            icon: 'error',
            title: 'Network Error',
            text: 'Please check your connection and try again.',
            confirmButtonColor: '#dc3545'
        });
    });
}

function cancelEdit() {
    toggleEditMode();
    // Reset form to original values
    location.reload();
}

function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(function() {
        // Show success toast
        Swal.fire({
            toast: true,
            position: 'top-end',
            icon: 'success',
            title: 'Copied to clipboard!',
            showConfirmButton: false,
            timer: 1500,
            timerProgressBar: true
        });
    }).catch(function(err) {
        console.error('Could not copy text: ', err);
        Swal.fire({
            toast: true,
            position: 'top-end',
            icon: 'error',
            title: 'Failed to copy',
            showConfirmButton: false,
            timer: 1500
        });
    });
}

function changeProfilePicture() {
    Swal.fire({
        title: 'Change Profile Picture',
        html: `
            <div class="profile-upload">
                <div class="upload-area" id="uploadArea">
                    <div class="upload-content">
                        <i class="fas fa-cloud-upload-alt upload-icon"></i>
                        <p>Click to select or drag & drop an image</p>
                        <small>Supported formats: JPG, PNG, GIF (Max: 5MB)</small>
                    </div>
                    <input type="file" id="profileImageInput" accept="image/*" style="display: none;">
                </div>
                <div class="image-preview" id="imagePreview" style="display: none;">
                    <img id="previewImg" src="" alt="Preview">
                    <button type="button" class="btn btn-sm btn-danger remove-preview" onclick="removePreview()">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
        `,
        width: '500px',
        showCancelButton: true,
        confirmButtonColor: '#28a745',
        cancelButtonColor: '#6c757d',
        confirmButtonText: 'Upload Image',
        cancelButtonText: 'Cancel',
        customClass: {
            popup: 'profile-upload-popup'
        },
        didOpen: () => {
            const uploadArea = document.getElementById('uploadArea');
            const fileInput = document.getElementById('profileImageInput');
            const imagePreview = document.getElementById('imagePreview');
            const previewImg = document.getElementById('previewImg');

            // Click to select file
            uploadArea.addEventListener('click', () => {
                fileInput.click();
            });

            // Drag and drop functionality
            uploadArea.addEventListener('dragover', (e) => {
                e.preventDefault();
                uploadArea.classList.add('drag-over');
            });

            uploadArea.addEventListener('dragleave', () => {
                uploadArea.classList.remove('drag-over');
            });

            uploadArea.addEventListener('drop', (e) => {
                e.preventDefault();
                uploadArea.classList.remove('drag-over');
                const files = e.dataTransfer.files;
                if (files.length > 0) {
                    handleFileSelect(files[0]);
                }
            });

            // File input change
            fileInput.addEventListener('change', (e) => {
                if (e.target.files.length > 0) {
                    handleFileSelect(e.target.files[0]);
                }
            });

            function handleFileSelect(file) {
                // Validate file
                if (!file.type.startsWith('image/')) {
                    Swal.showValidationMessage('Please select a valid image file');
                    return;
                }

                if (file.size > 5 * 1024 * 1024) { // 5MB limit
                    Swal.showValidationMessage('File size must be less than 5MB');
                    return;
                }

                // Show preview
                const reader = new FileReader();
                reader.onload = (e) => {
                    previewImg.src = e.target.result;
                    uploadArea.style.display = 'none';
                    imagePreview.style.display = 'block';
                    
                    // Store file for upload
                    Swal.getPopup().selectedFile = file;
                };
                reader.readAsDataURL(file);
            }

            window.removePreview = function() {
                uploadArea.style.display = 'block';
                imagePreview.style.display = 'none';
                fileInput.value = '';
                delete Swal.getPopup().selectedFile;
            };
        },
        preConfirm: () => {
            const selectedFile = Swal.getPopup().selectedFile;
            if (!selectedFile) {
                Swal.showValidationMessage('Please select an image to upload');
                return false;
            }
            return selectedFile;
        }
    }).then((result) => {
        if (result.isConfirmed && result.value) {
            uploadProfileImage(result.value);
        }
    });
}

function uploadProfileImage(file) {
    // Show upload progress
    Swal.fire({
        title: 'Uploading Image',
        html: `
            <div class="upload-progress">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
                <p style="margin-top: 15px;">Uploading your profile picture...</p>
                <div class="progress mt-3">
                    <div class="progress-bar progress-bar-striped progress-bar-animated" 
                         role="progressbar" style="width: 0%" id="uploadProgress"></div>
                </div>
            </div>
        `,
        allowOutsideClick: false,
        allowEscapeKey: false,
        showConfirmButton: false
    });

    // Create FormData for file upload
    const formData = new FormData();
    formData.append('profile_image', file);

    // Upload with progress tracking
    const xhr = new XMLHttpRequest();
    
    // Track upload progress
    xhr.upload.addEventListener('progress', (e) => {
        if (e.lengthComputable) {
            const percentComplete = (e.loaded / e.total) * 100;
            const progressBar = document.getElementById('uploadProgress');
            if (progressBar) {
                progressBar.style.width = percentComplete + '%';
            }
        }
    });

    xhr.onload = function() {
        if (xhr.status === 200) {
            try {
                const response = JSON.parse(xhr.responseText);
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Profile Picture Updated!',
                        text: 'Your profile picture has been updated successfully.',
                        timer: 2000,
                        timerProgressBar: true,
                        showConfirmButton: false
                    }).then(() => {
                        // Update the profile image on the page
                        const profileImg = document.querySelector('.profile-image');
                        if (profileImg) {
                            profileImg.src = response.imageUrl;
                        }
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Upload Failed',
                        text: response.message || 'Failed to upload image.',
                        confirmButtonColor: '#dc3545'
                    });
                }
            } catch (error) {
                Swal.fire({
                    icon: 'error',
                    title: 'Upload Error',
                    text: 'Invalid response from server.',
                    confirmButtonColor: '#dc3545'
                });
            }
        } else {
            Swal.fire({
                icon: 'error',
                title: 'Upload Failed',
                text: 'Server error occurred during upload.',
                confirmButtonColor: '#dc3545'
            });
        }
    };

    xhr.onerror = function() {
        Swal.fire({
            icon: 'error',
            title: 'Network Error',
            text: 'Please check your connection and try again.',
            confirmButtonColor: '#dc3545'
        });
    };

    xhr.open('POST', '<?php echo base_url('dashboard/upload_profile_image'); ?>');
    xhr.send(formData);
}
</script>