<div class="main">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="fd-3 mb-0">Change Password</h2>
        <a href="<?php echo base_url('dashboard/profile'); ?>" class="btn btn-outline-secondary">
            <i class="fas fa-arrow-left"></i> Back to Profile
        </a>
    </div>

    <!-- Flash Messages -->
    <?php if($this->session->flashdata('success')): ?>
        <script>
            document.addEventListener('DOMContentLoaded', function() {
                showSuccess('Success!', '<?php echo $this->session->flashdata('success'); ?>');
            });
        </script>
    <?php endif; ?>
    
    <?php if($this->session->flashdata('error')): ?>
        <script>
            document.addEventListener('DOMContentLoaded', function() {
                showError('Error!', '<?php echo $this->session->flashdata('error'); ?>');
            });
        </script>
    <?php endif; ?>

    <div class="row justify-content-center">
        <div class="col-md-8 col-lg-6">
            <div class="card shadow-sm">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0">
                        <i class="fas fa-key"></i> Update Your Password
                    </h5>
                </div>
                <div class="card-body p-4">
                    <form id="changePasswordForm" onsubmit="changePassword(event)">
                        <!-- New Password -->
                        <div class="mb-4">
                            <label for="newPassword" class="form-label">
                                <i class="fas fa-key"></i> New Password
                            </label>
                            <div class="input-group">
                                <input type="password" class="form-control" id="newPassword" name="newPassword" 
                                       placeholder="Enter your new password" required>
                                <button class="btn btn-outline-secondary" type="button" onclick="togglePassword('newPassword')">
                                    <i class="fas fa-eye" id="newPasswordIcon"></i>
                                </button>
                            </div>
                            <div class="form-text">
                                Password must be at least 8 characters long and contain uppercase, lowercase, number, and special character
                            </div>
                        </div>

                        <!-- Confirm New Password -->
                        <div class="mb-4">
                            <label for="confirmPassword" class="form-label">
                                <i class="fas fa-check-circle"></i> Confirm New Password
                            </label>
                            <div class="input-group">
                                <input type="password" class="form-control" id="confirmPassword" name="confirmPassword" 
                                       placeholder="Confirm your new password" required>
                                <button class="btn btn-outline-secondary" type="button" onclick="togglePassword('confirmPassword')">
                                    <i class="fas fa-eye" id="confirmPasswordIcon"></i>
                                </button>
                            </div>
                            <div class="form-text">Re-enter your new password to confirm</div>
                        </div>

                        <!-- Password Strength Indicator -->
                        <div class="mb-4">
                            <label class="form-label">Password Strength</label>
                            <div class="progress" style="height: 8px;">
                                <div class="progress-bar" id="passwordStrength" role="progressbar" style="width: 0%"></div>
                            </div>
                            <div class="form-text" id="passwordStrengthText">Enter a password to check strength</div>
                        </div>

                        <!-- Security Tips -->
                        <div class="alert alert-info mb-4">
                            <h6><i class="fas fa-shield-alt"></i> Password Requirements:</h6>
                            <ul class="mb-0">
                                <li>At least 8 characters long</li>
                                <li>Use a combination of uppercase and lowercase letters</li>
                                <li>Include numbers and special characters</li>
                                <li>Avoid using personal information</li>
                                <li>Don't reuse passwords from other accounts</li>
                            </ul>
                        </div>

                        <!-- Submit Button -->
                        <div class="d-grid gap-2">
                            <button type="submit" class="btn btn-primary btn-lg" id="submitBtn">
                                <span id="submitIcon">
                                    <i class="fas fa-key"></i> Update Password
                                </span>
                                <span class="spinner-border spinner-border-sm d-none" id="submitSpinner" role="status">
                                    <span class="visually-hidden">Loading...</span>
                                </span>
                            </button>
                            <a href="<?php echo base_url('dashboard/profile'); ?>" class="btn btn-outline-secondary">
                                <i class="fas fa-times"></i> Cancel
                            </a>
                        </div>
                    </form>
                </div>
            </div>

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

<style>
/* Password Change Specific Styles */
.card {
    border-radius: 15px;
    border: none;
}

.card-header {
    border-radius: 15px 15px 0 0 !important;
    border-bottom: none;
}

.form-control {
    border-radius: 10px;
    border: 2px solid #e9ecef;
    padding: 12px 15px;
    transition: all 0.3s ease;
}

.form-control:focus {
    border-color: #007bff;
    box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
    transform: translateY(-1px);
}

.input-group .btn {
    border-radius: 0 10px 10px 0;
    border: 2px solid #e9ecef;
    border-left: none;
}

.form-label {
    font-weight: 600;
    color: #495057;
    margin-bottom: 8px;
}

.form-text {
    font-size: 0.875rem;
    color: #6c757d;
    margin-top: 5px;
}

.btn-primary {
    background: linear-gradient(135deg, #007bff, #0056b3);
    border: none;
    border-radius: 10px;
    padding: 12px 20px;
    font-weight: 600;
    transition: all 0.3s ease;
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(0, 123, 255, 0.3);
}

.btn-outline-secondary {
    border-radius: 10px;
    border: 2px solid #6c757d;
    padding: 10px 20px;
    transition: all 0.3s ease;
}

.btn-outline-secondary:hover {
    transform: translateY(-1px);
    box-shadow: 0 3px 10px rgba(108, 117, 125, 0.2);
}

.alert {
    border-radius: 10px;
    border: none;
}

.alert-info {
    background: linear-gradient(135deg, #d1ecf1, #bee5eb);
    color: #0c5460;
}

.alert-warning {
    background: linear-gradient(135deg, #fff3cd, #ffeeba);
    color: #856404;
}

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

.progress-bar {
    border-radius: 10px;
    transition: all 0.5s ease;
}

.badge {
    border-radius: 20px;
    padding: 5px 10px;
    font-size: 0.8rem;
}

/* Password Strength Colors */
.progress-bar.weak {
    background-color: #dc3545;
}

.progress-bar.fair {
    background-color: #ffc107;
}

.progress-bar.good {
    background-color: #17a2b8;
}

.progress-bar.strong {
    background-color: #28a745;
}

/* Responsive */
@media (max-width: 768px) {
    .main {
        padding: 15px;
    }
    
    .card-body {
        padding: 20px !important;
    }
    
    .form-control {
        padding: 10px 12px;
    }
}
</style>

<script>
// Change password functionality
function changePassword(event) {
    event.preventDefault();
    
    const newPassword = document.getElementById('newPassword').value.trim();
    const confirmPassword = document.getElementById('confirmPassword').value.trim();
    
    // Validation
    if (!newPassword) {
        showWarning('Validation Error', 'Please enter a new password');
        return;
    }
    
    if (newPassword.length < 8) {
        showWarning('Validation Error', 'New password must be at least 8 characters long');
        return;
    }
    
    if (newPassword !== confirmPassword) {
        showWarning('Validation Error', 'New password and confirmation do not match');
        return;
    }
    
    // Check password strength
    const strength = getPasswordStrength(newPassword);
    if (strength < 3) {
        showConfirm(
            'Weak Password', 
            'Your password is weak. Are you sure you want to continue?',
            'Yes, Continue',
            'No, Let me improve it'
        ).then((result) => {
            if (result.isConfirmed) {
                submitPasswordChange();
            }
        });
        return;
    }
    
    submitPasswordChange();
}

// Submit password change
function submitPasswordChange() {
    setLoadingState(true);
    
    const formData = new FormData();
    formData.append('newPassword', document.getElementById('newPassword').value);
    formData.append('confirmPassword', document.getElementById('confirmPassword').value);
    
    fetch('<?php echo base_url("dashboard/update_password"); ?>', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showSuccess('Password Updated!', data.message).then(() => {
                // Redirect to profile or login
                window.location.href = '<?php echo base_url("dashboard/profile"); ?>';
            });
        } else {
            showError('Error', data.message || 'Failed to update password');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showError('Error', 'Network error. Please try again.');
    })
    .finally(() => {
        setLoadingState(false);
    });
}

// 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.className = 'fas fa-eye-slash';
    } else {
        field.type = 'password';
        icon.className = 'fas fa-eye';
    }
}

// Set loading state
function setLoadingState(loading) {
    const submitBtn = document.getElementById('submitBtn');
    const submitIcon = document.getElementById('submitIcon');
    const submitSpinner = document.getElementById('submitSpinner');
    
    if (loading) {
        submitBtn.disabled = true;
        submitIcon.classList.add('d-none');
        submitSpinner.classList.remove('d-none');
    } else {
        submitBtn.disabled = false;
        submitIcon.classList.remove('d-none');
        submitSpinner.classList.add('d-none');
    }
}

// Password strength checker
function getPasswordStrength(password) {
    let strength = 0;
    
    // Length check
    if (password.length >= 8) strength++;
    if (password.length >= 12) strength++;
    
    // Character variety checks
    if (/[a-z]/.test(password)) strength++;
    if (/[A-Z]/.test(password)) strength++;
    if (/[0-9]/.test(password)) strength++;
    if (/[^A-Za-z0-9]/.test(password)) strength++;
    
    return strength;
}

// Update password strength indicator
function updatePasswordStrength() {
    const password = document.getElementById('newPassword').value;
    const strengthBar = document.getElementById('passwordStrength');
    const strengthText = document.getElementById('passwordStrengthText');
    
    const strength = getPasswordStrength(password);
    let percentage = 0;
    let text = '';
    let className = '';
    
    if (password.length === 0) {
        text = 'Enter a password to check strength';
        className = '';
    } else if (strength <= 2) {
        percentage = 25;
        text = 'Weak - Add more variety';
        className = 'weak';
    } else if (strength <= 3) {
        percentage = 50;
        text = 'Fair - Could be stronger';
        className = 'fair';
    } else if (strength <= 4) {
        percentage = 75;
        text = 'Good - Nice password';
        className = 'good';
    } else {
        percentage = 100;
        text = 'Strong - Excellent password';
        className = 'strong';
    }
    
    strengthBar.style.width = percentage + '%';
    strengthBar.className = `progress-bar ${className}`;
    strengthText.textContent = text;
}

// Event listeners
document.addEventListener('DOMContentLoaded', function() {
    const newPasswordField = document.getElementById('newPassword');
    if (newPasswordField) {
        newPasswordField.addEventListener('input', updatePasswordStrength);
    }
    
    // Real-time password confirmation validation
    const confirmPasswordField = document.getElementById('confirmPassword');
    const newPasswordFieldForConfirm = document.getElementById('newPassword');
    
    function validatePasswordMatch() {
        const newPass = newPasswordFieldForConfirm.value;
        const confirmPass = confirmPasswordField.value;
        
        if (confirmPass && newPass !== confirmPass) {
            confirmPasswordField.setCustomValidity('Passwords do not match');
            confirmPasswordField.classList.add('is-invalid');
        } else {
            confirmPasswordField.setCustomValidity('');
            confirmPasswordField.classList.remove('is-invalid');
            if (confirmPass && newPass === confirmPass) {
                confirmPasswordField.classList.add('is-valid');
            }
        }
    }
    
    if (confirmPasswordField && newPasswordFieldForConfirm) {
        confirmPasswordField.addEventListener('input', validatePasswordMatch);
        newPasswordFieldForConfirm.addEventListener('input', validatePasswordMatch);
    }
});
</script>
