<!-- Change Password Modal -->
<style>
    /* Clean, modern styling for password modal */
    #changePasswordModal .form-group { 
        margin-bottom: 1.5rem; 
    }
    
    #changePasswordModal .form-control {
        background: #232b36;
        color: #bfc9d4;
        border: 1px solid #2c3642;
        border-radius: 4px;
        height: 40px;
        padding: 8px 12px;
        line-height: 1.42857143;
    }
    
    #changePasswordModal .form-control:focus {
        background: #232b36;
        color: #fff;
        border-color: #3a4654;
        box-shadow: none;
    }
    
    /* Bootstrap 5 input group styling */
    #changePasswordModal .input-group {
        margin-bottom: 0.75rem;
    }
    
    #changePasswordModal .input-group .btn {
        background: #2c3642;
        border: 1px solid #2c3642;
        border-left: none;
        color: #bfc9d4;
        padding: 8px 12px;
        height: 40px;
        line-height: 1.42857143;
    }
    
    #changePasswordModal .input-group .btn:hover,
    #changePasswordModal .input-group .btn:focus {
        background: #3a4654;
        color: #5bc0de;
        border-color: #3a4654;
    }
    
    /* Generate button styling */
    #changePasswordModal .btn-generate {
        background: #1a8cff;
        color: #fff;
        border: none;
        border-radius: 4px;
        padding: 0.4rem 1rem;
        font-size: 0.9rem;
        transition: background 0.2s;
        margin-bottom: 0.5rem;
    }
    
    #changePasswordModal .btn-generate:hover, 
    #changePasswordModal .btn-generate:focus {
        background: #006bb3;
        color: #fff;
    }
    
    /* Progress and validation styling */
    #changePasswordModal #passwordStrength { 
        margin-top: 0.5rem; 
        margin-bottom: 0.5rem; 
    }
    
    #changePasswordModal #passwordMatch { 
        margin-top: 0.5rem; 
        margin-bottom: 0.5rem; 
    }
    
    #changePasswordModal .alert-info {
        background: #3a4654;
        color: #fff;
        border: none;
        border-radius: 4px;
    }
    
    /* Bootstrap 5 input group border radius fixes */
    #changePasswordModal .input-group .form-control:not(:first-child):not(:last-child) {
        border-radius: 0;
    }
    
    #changePasswordModal .input-group .form-control:first-child {
        border-top-right-radius: 0;
        border-bottom-right-radius: 0;
    }
    
    #changePasswordModal .input-group .btn:last-child {
        border-top-left-radius: 0;
        border-bottom-left-radius: 0;
        margin-left: -1px;
    }
    
    /* Right-align utility for generate button */
    #changePasswordModal .text-right {
        text-align: right;
    }
</style>

<div class="modal fade" id="changePasswordModal" tabindex="-1" role="dialog" aria-labelledby="changePasswordModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="changePasswordModalLabel">
                    <i class="fa fa-key"></i> Change Password
                </h4>
            </div>
            <div class="modal-body">
                <form id="changePasswordForm">
                    <!-- Current Password -->
                    <div class="form-group">
                        <label for="currentPassword">Current Password</label>
                        <div class="input-group">
                            <input type="password" class="form-control" id="currentPassword" required autocomplete="current-password">
                            <button type="button" class="btn" id="toggleCurrentPassword" tabindex="-1" aria-label="Show password">
                                <i class="fa fa-eye" id="currentPasswordIcon"></i>
                            </button>
                        </div>
                    </div>
                    
                    <!-- New Password -->
                    <div class="form-group">
                        <label for="newPassword">New Password</label>
                        <div class="input-group">
                            <input type="password" class="form-control" id="newPassword" required autocomplete="new-password">
                            <button type="button" class="btn" id="togglePassword" tabindex="-1" aria-label="Show password">
                                <i class="fa fa-eye" id="newPasswordIcon"></i>
                            </button>
                        </div>
                        
                        <!-- Generate Button -->
                        <div class="text-right">
                            <button type="button" class="btn btn-generate" id="generatePassword">
                                <i class="fa fa-magic"></i> Generate
                            </button>
                        </div>
                        
                        <!-- Password Strength -->
                        <div id="passwordStrength" style="display: none;">
                            <div class="progress" style="height: 5px;">
                                <div class="progress-bar" role="progressbar" style="width: 0%"></div>
                            </div>
                            <small id="strengthText" class="text-muted"></small>
                        </div>
                    </div>
                    
                    <!-- Confirm Password -->
                    <div class="form-group">
                        <label for="confirmPassword">Confirm New Password</label>
                        <div class="input-group">
                            <input type="password" class="form-control" id="confirmPassword" required autocomplete="new-password">
                            <button type="button" class="btn" id="toggleConfirmPassword" tabindex="-1" aria-label="Show password">
                                <i class="fa fa-eye" id="confirmPasswordIcon"></i>
                            </button>
                        </div>
                        
                        <!-- Password Match -->
                        <div id="passwordMatch" style="display: none;">
                            <small id="matchText"></small>
                        </div>
                    </div>
                    
                    <!-- Password Requirements -->
                    <div class="alert alert-info">
                        <h5><i class="fa fa-info-circle"></i> Password Requirements</h5>
                        <ul class="mb-0">
                            <li>At least 8 characters long (12+ recommended)</li>
                            <li>Include uppercase and lowercase letters</li>
                            <li>Include numbers and symbols</li>
                            <li>Avoid common words and sequences</li>
                        </ul>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="savePassword">Change Password</button>
            </div>
        </div>
    </div>
</div>

<!-- Password Change JavaScript -->
<script>
$(document).ready(function() {
    var passwordStrengthTimer;
    var confirmPasswordTimer;
    var revealTimers = {};
    
    // Get CSRF token for API requests
    var csrfToken = '<?php echo isset($_SESSION['csrf_token']) ? $_SESSION['csrf_token'] : ''; ?>';
    
    // Simplified toggle function using Font Awesome icons
    function togglePasswordField($input, $iconElement) {
        var inputId = $input.attr('id');
        var isVisible = $input.attr('type') === 'text';
        
        if (isVisible) {
            // Hide password
            $input.attr('type', 'password');
            $iconElement.removeClass('fa-eye-slash').addClass('fa-eye');
            $input.closest('.input-group').find('button').attr('aria-label', 'Show password');
            
            // Clear auto-hide timer
            if (revealTimers[inputId]) {
                clearTimeout(revealTimers[inputId]);
                revealTimers[inputId] = null;
            }
        } else {
            // Show password
            $input.attr('type', 'text');
            $iconElement.removeClass('fa-eye').addClass('fa-eye-slash');
            $input.closest('.input-group').find('button').attr('aria-label', 'Hide password');
            
            // Auto-hide after 10 seconds
            if (revealTimers[inputId]) clearTimeout(revealTimers[inputId]);
            revealTimers[inputId] = setTimeout(function() {
                $input.attr('type', 'password');
                $iconElement.removeClass('fa-eye-slash').addClass('fa-eye');
                $input.closest('.input-group').find('button').attr('aria-label', 'Show password');
            }, 10000);
        }
    }
    
    // Toggle event handlers
    $('#toggleCurrentPassword').on('click', function() {
        togglePasswordField($('#currentPassword'), $('#currentPasswordIcon'));
    });
    
    $('#togglePassword').on('click', function() {
        togglePasswordField($('#newPassword'), $('#newPasswordIcon'));
    });
    
    $('#toggleConfirmPassword').on('click', function() {
        togglePasswordField($('#confirmPassword'), $('#confirmPasswordIcon'));
    });
    
    // Generate password button
    $('#generatePassword').click(function() {
        $.ajax({
            url: '/api/change-password.php?action=generate&length=16',
            method: 'GET',
            headers: {
                'X-CSRF-Token': csrfToken
            }
        })
            .done(function(response) {
                if (response.status === 'success') {
                    $('#newPassword').val(response.data.password);
                    $('#confirmPassword').val(response.data.password);
                    updatePasswordStrength(response.data.password);
                    updatePasswordMatch();
                    
                    // Show passwords briefly when generated
                    var $newInput = $('#newPassword');
                    var $confirmInput = $('#confirmPassword');
                    var $newIcon = $('#newPasswordIcon');
                    var $confirmIcon = $('#confirmPasswordIcon');
                    
                    $newInput.attr('type', 'text');
                    $confirmInput.attr('type', 'text');
                    $newIcon.removeClass('fa-eye').addClass('fa-eye-slash');
                    $confirmIcon.removeClass('fa-eye').addClass('fa-eye-slash');
                    
                    // Auto-hide after 10 seconds
                    if (revealTimers['newPassword']) clearTimeout(revealTimers['newPassword']);
                    if (revealTimers['confirmPassword']) clearTimeout(revealTimers['confirmPassword']);
                    
                    revealTimers['newPassword'] = setTimeout(function() {
                        $newInput.attr('type', 'password');
                        $newIcon.removeClass('fa-eye-slash').addClass('fa-eye');
                    }, 10000);
                    
                    revealTimers['confirmPassword'] = setTimeout(function() {
                        $confirmInput.attr('type', 'password');
                        $confirmIcon.removeClass('fa-eye-slash').addClass('fa-eye');
                    }, 10000);
                } else {
                    alert('Error generating password: ' + response.message);
                }
            })
            .fail(function() {
                alert('Error generating password. Please try again.');
            });
    });
    
    // Check password strength on input
    $('#newPassword').on('input', function() {
        clearTimeout(passwordStrengthTimer);
        var password = $(this).val();
        
        if (password.length > 0) {
            passwordStrengthTimer = setTimeout(function() {
                checkPasswordStrength(password);
            }, 300);
        } else {
            $('#passwordStrength').hide();
        }
    });
    
    // Check password match on input
    $('#confirmPassword').on('input', function() {
        clearTimeout(confirmPasswordTimer);
        confirmPasswordTimer = setTimeout(function() {
            updatePasswordMatch();
        }, 300);
    });
    
    // Check password strength via API
    function checkPasswordStrength(password) {
        $.ajax({
            url: '/api/change-password.php?action=check-strength&password=' + encodeURIComponent(password),
            method: 'GET',
            headers: {
                'X-CSRF-Token': csrfToken
            }
        })
            .done(function(response) {
                if (response.status === 'success') {
                    updatePasswordStrength(password, response.data);
                }
            })
            .fail(function() {
                // Fallback to client-side check if API fails
                updatePasswordStrength(password);
            });
    }
    
    // Update password strength display
    function updatePasswordStrength(password, serverData) {
        var $progress = $('#passwordStrength .progress-bar');
        var $text = $('#strengthText');
        var strength, score, color, text;
        
        if (serverData) {
            strength = serverData;
            score = strength.score;
        } else {
            // Enhanced client-side strength check
            score = 0;
            var checks = 0;
            
            // Length checks
            if (password.length >= 12) {
                score += 2;
                checks++;
            } else if (password.length >= 8) {
                score += 1;
                checks++;
            }
            
            // Character variety checks
            if (password.match(/[a-z]/)) { score++; checks++; }
            if (password.match(/[A-Z]/)) { score++; checks++; }
            if (password.match(/[0-9]/)) { score++; checks++; }
            if (password.match(/[^a-zA-Z0-9]/)) { score++; checks++; }
            
            // Penalty for common patterns
            if (password.match(/(.)\1{2,}/)) score--; // repeated characters
            if (password.match(/(123|abc|qwe|asd|zxc)/i)) score--; // sequences
            
            // Normalize score to 1-5 range
            score = Math.max(1, Math.min(5, score));
            
            strength = {
                score: score,
                feedback: []
            };
        }
        
        // Set color and text based on score
        switch (strength.score) {
            case 1:
                color = '#dc3545'; text = 'Very Weak'; break;
            case 2:
                color = '#fd7e14'; text = 'Weak'; break;
            case 3:
                color = '#ffc107'; text = 'Fair'; break;
            case 4:
                color = '#17a2b8'; text = 'Good'; break;
            case 5:
                color = '#28a745'; text = 'Strong'; break;
            default:
                // This should never happen with the normalized score
                color = '#dc3545'; text = 'Very Weak'; score = 1;
        }
        
        var percentage = ((strength.score - 1) / 4) * 100; // Scale 1-5 to 0-100%
        $progress.css({
            'width': percentage + '%',
            'background-color': color
        });
        $text.text(text);
        $('#passwordStrength').show();
    }
    
    // Update password match display
    function updatePasswordMatch() {
        var newPass = $('#newPassword').val();
        var confirmPass = $('#confirmPassword').val();
        
        if (confirmPass.length > 0) {
            if (newPass === confirmPass) {
                $('#matchText')
                    .text('✓ Passwords match')
                    .removeClass('text-danger')
                    .addClass('text-success');
            } else {
                $('#matchText')
                    .text('✗ Passwords do not match')
                    .removeClass('text-success')
                    .addClass('text-danger');
            }
            $('#passwordMatch').show();
        } else {
            $('#passwordMatch').hide();
        }
    }
    
    // Save password button
    $('#savePassword').click(function() {
        var currentPass = $('#currentPassword').val();
        var newPass = $('#newPassword').val();
        var confirmPass = $('#confirmPassword').val();
        
        if (!currentPass || !newPass || !confirmPass) {
            alert('Please fill in all password fields.');
            return;
        }
        
        if (newPass !== confirmPass) {
            alert('New passwords do not match.');
            return;
        }
        
        // Disable button and show loading
        var $btn = $(this);
        var originalText = $btn.text();
        $btn.prop('disabled', true).text('Changing...');
        
        $.ajax({
            url: '/api/change-password.php',
            method: 'POST',
            contentType: 'application/json',
            headers: {
                'X-CSRF-Token': csrfToken
            },
            data: JSON.stringify({
                current_password: currentPass,
                new_password: newPass,
                confirm_password: confirmPass
            })
        })
        .done(function(response) {
            if (response.status === 'success') {
                alert('Password changed successfully!');
                // Bootstrap 5 modal API
                var modalElement = document.getElementById('changePasswordModal');
                var modal = bootstrap.Modal.getInstance(modalElement) || new bootstrap.Modal(modalElement);
                modal.hide();
                $('#changePasswordForm')[0].reset();
                $('#passwordStrength, #passwordMatch').hide();
            } else {
                alert('Error: ' + response.message);
            }
        })
        .fail(function(xhr) {
            var message = 'An error occurred while changing the password.';
            if (xhr.responseJSON && xhr.responseJSON.message) {
                message = xhr.responseJSON.message;
            }
            alert('Error: ' + message);
        })
        .always(function() {
            $btn.prop('disabled', false).text(originalText);
        });
    });
    
    // Reset form when modal is hidden
    $('#changePasswordModal').on('hidden.bs.modal', function() {
        $('#changePasswordForm')[0].reset();
        $('#passwordStrength, #passwordMatch').hide();
        
        // Reset all password field states
        ['currentPassword', 'newPassword', 'confirmPassword'].forEach(function(id) {
            var $input = $('#' + id);
            var $icon = $('#' + id + 'Icon');
            $input.attr('type', 'password');
            $icon.removeClass('fa-eye-slash').addClass('fa-eye');
            if (revealTimers[id]) {
                clearTimeout(revealTimers[id]);
                revealTimers[id] = null;
            }
        });
    });
});
</script> 