<?php
// Start session if not already started
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

require_once './includes/config.php';
require_once './includes/auth_functions.php';

// Ensure $pdo is defined and valid
if (!isset($pdo)) {
    die("Database connection is not initialized.");
}

// Check if the member is forced to reset their password
if (!isset($_SESSION['force_password_reset'])) {
    header("Location: login.php");
    exit;
}

// Check if $_SESSION['member_id'] is set
if (!isset($_SESSION['member_id'])) {
    die("Member ID is not set in the session. Please log in again.");
}

// Generate CSRF token if it doesn't exist
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Handle password reset form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Validate CSRF token
    if (empty($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        logSecurityEvent($_SESSION['member_id'], 'csrf_failure', 'password_reset');
        die("Invalid request. Please try again.");
    }

    $newPassword = $_POST['new_password'];
    $confirmPassword = $_POST['confirm_password'];

    // Validate that passwords match
    if ($newPassword === $confirmPassword) {
        // Validate password complexity
        if (strlen($newPassword) >= 8 && 
            preg_match('/[A-Z]/', $newPassword) && 
            preg_match('/[a-z]/', $newPassword) && 
            preg_match('/[0-9]/', $newPassword) && 
            preg_match('/[^A-Za-z0-9]/', $newPassword) // Ensure at least one special character
        ) {
            try {
                // Fetch the current password hash from the database
                $stmt = $pdo->prepare("SELECT password_hash FROM member_portal_accounts WHERE member_id = :id");
                $stmt->execute(['id' => $_SESSION['member_id']]);
                $account = $stmt->fetch(PDO::FETCH_ASSOC);

                if ($account) {
                    // Check if the new password is different from the old one
                    if (password_verify($newPassword, $account['password_hash'])) {
                        $error = 'New password must be different from the old password.';
                    } else {
                        // Hash the new password
                        $hashedPassword = password_hash($newPassword, PASSWORD_BCRYPT);

                        // Update the password and password_last_changed timestamp
                        $stmt = $pdo->prepare("
                            UPDATE member_portal_accounts 
                            SET password_hash = :password, password_last_changed = CURRENT_TIMESTAMP 
                            WHERE member_id = :id
                        ");
                        $stmt->execute([
                            'password' => $hashedPassword,
                            'id' => $_SESSION['member_id'],
                        ]);

                        // Log the password reset event
                        logSecurityEvent($_SESSION['member_id'], 'password_reset_success', [
                            'ip' => $_SERVER['REMOTE_ADDR']
                        ]);

                        // Send email notification
                        sendPasswordResetEmail($_SESSION['member_id']);

                        // Clear the force password reset flag
                        unset($_SESSION['force_password_reset']);

                        // Clear the CSRF token after successful password reset
                        unset($_SESSION['csrf_token']);

                        // Log out the member by destroying the session
                        session_unset();
                        session_destroy();

                        // Redirect to the login page with success message
                        $_SESSION['success_message'] = 'Password reset successfully. Please log in with your new password.';
                        header("Location: login.php");
                        exit;
                    }
                } else {
                    $error = 'Member account not found.';
                    logSecurityEvent($_SESSION['member_id'], 'password_reset_error', [
                        'error' => 'Member account not found',
                        'ip' => $_SERVER['REMOTE_ADDR']
                    ]);
                }
            } catch (PDOException $e) {
                error_log("Password reset error: " . $e->getMessage());
                $error = 'An error occurred while updating your password. Please try again.';
                logSecurityEvent($_SESSION['member_id'], 'password_reset_error', [
                    'error' => $e->getMessage(),
                    'ip' => $_SERVER['REMOTE_ADDR']
                ]);
            }
        } else {
            $error = 'Password must be at least 8 characters long and include uppercase, lowercase, numbers, and at least one special character.';
            logSecurityEvent($_SESSION['member_id'], 'password_complexity_failed', [
                'ip' => $_SERVER['REMOTE_ADDR']
            ]);
        }
    } else {
        $error = 'Passwords do not match.';
        logSecurityEvent($_SESSION['member_id'], 'password_mismatch', [
            'ip' => $_SERVER['REMOTE_ADDR']
        ]);
    }
}

/**
 * Send a password reset email using PHPMailer.
 *
 * @param int $memberId The ID of the member whose password was reset.
 */
function sendPasswordResetEmail($memberId) {
    global $pdo;

    // Load SMTP configuration
    $smtpConfig = loadSmtpConfig();

    // Fetch member email
    try {
        $stmt = $pdo->prepare("
            SELECT a.email, m.first_name, m.last_name 
            FROM member_portal_accounts a
            JOIN members m ON m.id = a.member_id
            WHERE a.member_id = :id
        ");
        $stmt->execute(['id' => $memberId]);
        $member = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($member) {
            require_once __DIR__ . '/./vendor/autoload.php';

            $mail = new PHPMailer\PHPMailer\PHPMailer(true);

            try {
                // SMTP configuration
                $mail->isSMTP();
                $mail->Host = $smtpConfig['smtp_host'];
                $mail->SMTPAuth = true;
                $mail->Username = $smtpConfig['smtp_username'];
                $mail->Password = $smtpConfig['smtp_password'];
                $mail->SMTPSecure = $smtpConfig['smtp_encryption'];
                $mail->Port = $smtpConfig['smtp_port'];

                // Email content
                $mail->setFrom($smtpConfig['smtp_username'], 'Member Portal Password Reset');
                $mail->addAddress($member['email']);

                $mail->isHTML(true);
                $mail->Subject = 'Password Reset Successful';
                $mail->Body = "
                    <h2>Password Reset Successful</h2>
                    <p>Hello " . htmlspecialchars($member['first_name']) . ",</p>
                    <p>Your password has been successfully reset. If you did not initiate this change, please contact support immediately.</p>
                    <p>Thank you,<br>Member Portal Team</p>
                ";
                $mail->AltBody = "Hello " . $member['first_name'] . ",\n\nYour password has been successfully reset. If you did not initiate this change, please contact support immediately.\n\nThank you,\nMember Portal Team";

                // Send email
                $mail->send();
                logSecurityEvent($memberId, 'password_reset_email_sent', [
                    'email' => $member['email']
                ]);
            } catch (Exception $e) {
                error_log("Failed to send password reset email: " . $mail->ErrorInfo);
                logSecurityEvent($memberId, 'password_reset_email_failed', [
                    'error' => $mail->ErrorInfo
                ]);
            }
        } else {
            error_log("Member not found for ID: " . $memberId);
        }
    } catch (PDOException $e) {
        error_log("Error fetching member email: " . $e->getMessage());
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Force Password Reset | Member Portal</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
        
        :root {
            --primary: #2563eb;
            --primary-dark: #1d4ed8;
            --secondary: #64748b;
            --success: #10b981;
            --danger: #ef4444;
            --warning: #f59e0b;
            --light: #f8fafc;
            --dark: #1e293b;
            --gray: #94a3b8;
            --border: #e2e8f0;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Inter', sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            padding: 20px;
        }
        
        .reset-container {
            background: white;
            border-radius: 16px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 440px;
            overflow: hidden;
            animation: fadeIn 0.5s ease-out;
        }
        
        .reset-header {
            background: var(--primary);
            color: white;
            padding: 24px 32px;
            text-align: center;
            position: relative;
        }
        
        .security-indicator {
            position: absolute;
            top: 10px;
            right: 10px;
            display: flex;
            align-items: center;
            gap: 5px;
            font-size: 12px;
            background: rgba(255, 255, 255, 0.2);
            padding: 4px 8px;
            border-radius: 12px;
        }
        
        .reset-header h1 {
            font-size: 24px;
            font-weight: 600;
            margin-bottom: 8px;
        }
        
        .reset-header p {
            font-size: 14px;
            opacity: 0.9;
        }
        
        .reset-body {
            padding: 32px;
        }
        
        .logo {
            margin-bottom: 24px;
            text-align: center;
        }
        
        .logo img {
            height: 60px;
        }
        
        .form-group {
            margin-bottom: 20px;
            position: relative;
        }
        
        label {
            display: block;
            font-size: 14px;
            font-weight: 500;
            margin-bottom: 8px;
            color: var(--dark);
        }
        
        .input-group {
            position: relative;
        }
        
        input[type="password"] {
            width: 100%;
            padding: 12px 16px;
            padding-right: 40px;
            border: 1px solid var(--border);
            border-radius: 8px;
            font-size: 15px;
            transition: all 0.2s;
        }
        
        input[type="password"]:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
            outline: none;
        }
        
        .toggle-password {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: var(--gray);
            cursor: pointer;
            padding: 4px;
            z-index: 2;
        }
        
        .toggle-password:hover {
            color: var(--secondary);
        }
        
        .password-strength {
            margin-top: 8px;
            height: 4px;
            background-color: #e2e8f0;
            border-radius: 2px;
            overflow: hidden;
        }
        
        .strength-meter {
            height: 100%;
            width: 0%;
            transition: width 0.3s ease;
        }
        
        .password-requirements {
            margin-top: 8px;
            font-size: 12px;
            color: var(--secondary);
        }
        
        .requirement {
            display: flex;
            align-items: center;
            gap: 5px;
            margin-bottom: 4px;
        }
        
        .requirement i {
            font-size: 10px;
        }
        
        .requirement.met {
            color: var(--success);
        }
        
        .submit-btn {
            width: 100%;
            padding: 14px;
            background-color: var(--primary);
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: background 0.2s;
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 8px;
        }
        
        .submit-btn:hover {
            background-color: var(--primary-dark);
        }
        
        .submit-btn:active {
            transform: translateY(1px);
        }
        
        .submit-btn.loading {
            opacity: 0.8;
            pointer-events: none;
        }
        
        .spinner {
            width: 18px;
            height: 18px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s linear infinite;
        }
        
        .error-message {
            background-color: rgba(239, 68, 68, 0.1);
            color: var(--danger);
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 10px;
            border-left: 4px solid var(--danger);
        }
        
        .privacy-notice {
            font-size: 12px;
            color: var(--secondary);
            margin-top: 16px;
            text-align: center;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        @keyframes shake {
            0%, 100% { transform: translateX(0); }
            10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
            20%, 40%, 60%, 80% { transform: translateX(5px); }
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        @media (max-width: 480px) {
            .reset-container {
                border-radius: 12px;
            }
            
            .reset-header {
                padding: 20px;
            }
            
            .reset-body {
                padding: 24px;
            }
        }
    </style>
</head>
<body>
    <div class="reset-container">
        <div class="reset-header">
            <div class="security-indicator">
                <i class="fas fa-lock"></i>
                <span>Secure</span>
            </div>
            <h1>Password Reset Required</h1>
            <p>Your password has expired. Please reset it to continue.</p>
        </div>
        
        <div class="reset-body">
            <div class="logo">
                <!-- Replace with your SACCO logo -->
                <svg width="60" height="60" viewBox="0 0 60 60" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <rect width="60" height="60" rx="12" fill="#2563eb"/>
                    <path d="M20 30L26 36L40 22" stroke="white" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
            </div>
            
            <?php if (!empty($error)): ?>
                <div class="error-message">
                    <i class="fas fa-exclamation-circle"></i>
                    <span><?php echo htmlspecialchars($error); ?></span>
                </div>
            <?php endif; ?>
            
            <form method="POST" id="resetForm">
                <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">

                <div class="form-group">
                    <label for="new_password">New Password</label>
                    <div class="input-group">
                        <input type="password" id="new_password" name="new_password" required placeholder="Enter new password">
                        <button type="button" class="toggle-password" id="toggleNewPassword">
                            <i class="fas fa-eye"></i>
                        </button>
                    </div>
                    <div class="password-strength" id="passwordStrength">
                        <div class="strength-meter" id="strengthMeter"></div>
                    </div>
                    <div class="password-requirements" id="passwordRequirements">
                        <div class="requirement" id="reqLength">
                            <i class="fas fa-circle"></i>
                            <span>At least 8 characters</span>
                        </div>
                        <div class="requirement" id="reqUppercase">
                            <i class="fas fa-circle"></i>
                            <span>One uppercase letter</span>
                        </div>
                        <div class="requirement" id="reqLowercase">
                            <i class="fas fa-circle"></i>
                            <span>One lowercase letter</span>
                        </div>
                        <div class="requirement" id="reqNumber">
                            <i class="fas fa-circle"></i>
                            <span>One number</span>
                        </div>
                        <div class="requirement" id="reqSpecial">
                            <i class="fas fa-circle"></i>
                            <span>One special character</span>
                        </div>
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="confirm_password">Confirm Password</label>
                    <div class="input-group">
                        <input type="password" id="confirm_password" name="confirm_password" required placeholder="Confirm new password">
                        <button type="button" class="toggle-password" id="toggleConfirmPassword">
                            <i class="fas fa-eye"></i>
                        </button>
                    </div>
                </div>
                
                <button type="submit" class="submit-btn" id="resetButton">
                    <span>Reset Password</span>
                    <div class="spinner" style="display: none;"></div>
                </button>
                
                <div class="privacy-notice">
                    <i class="fas fa-shield-alt"></i>
                    Your password information is encrypted and secure
                </div>
            </form>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const resetForm = document.getElementById('resetForm');
            const resetButton = document.getElementById('resetButton');
            const toggleNewPassword = document.getElementById('toggleNewPassword');
            const toggleConfirmPassword = document.getElementById('toggleConfirmPassword');
            const newPasswordInput = document.getElementById('new_password');
            const confirmPasswordInput = document.getElementById('confirm_password');
            const passwordStrength = document.getElementById('passwordStrength');
            const strengthMeter = document.getElementById('strengthMeter');
            
            // Toggle password visibility
            function setupPasswordToggle(toggleButton, passwordInput) {
                toggleButton.addEventListener('click', function() {
                    const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
                    passwordInput.setAttribute('type', type);
                    
                    // Toggle eye icon
                    const eyeIcon = this.querySelector('i');
                    eyeIcon.classList.toggle('fa-eye');
                    eyeIcon.classList.toggle('fa-eye-slash');
                });
            }
            
            setupPasswordToggle(toggleNewPassword, newPasswordInput);
            setupPasswordToggle(toggleConfirmPassword, confirmPasswordInput);
            
            // Password strength indicator
            newPasswordInput.addEventListener('input', function() {
                const password = this.value;
                
                // Check requirements
                const hasLength = password.length >= 8;
                const hasUppercase = /[A-Z]/.test(password);
                const hasLowercase = /[a-z]/.test(password);
                const hasNumber = /[0-9]/.test(password);
                const hasSpecial = /[^A-Za-z0-9]/.test(password);
                
                // Update requirement indicators
                document.getElementById('reqLength').classList.toggle('met', hasLength);
                document.getElementById('reqUppercase').classList.toggle('met', hasUppercase);
                document.getElementById('reqLowercase').classList.toggle('met', hasLowercase);
                document.getElementById('reqNumber').classList.toggle('met', hasNumber);
                document.getElementById('reqSpecial').classList.toggle('met', hasSpecial);
                
                // Calculate strength
                let strength = 0;
                if (hasLength) strength += 20;
                if (hasUppercase) strength += 20;
                if (hasLowercase) strength += 20;
                if (hasNumber) strength += 20;
                if (hasSpecial) strength += 20;
                
                strengthMeter.style.width = strength + '%';
                
                // Set color based on strength
                if (strength < 60) {
                    strengthMeter.style.backgroundColor = '#ef4444'; // red
                } else if (strength < 100) {
                    strengthMeter.style.backgroundColor = '#f59e0b'; // orange
                } else {
                    strengthMeter.style.backgroundColor = '#10b981'; // green
                }
            });
            
            // Form submission
            resetForm.addEventListener('submit', function(e) {
                // Basic validation
                const newPassword = newPasswordInput.value;
                const confirmPassword = confirmPasswordInput.value;
                
                if (!newPassword || !confirmPassword) {
                    e.preventDefault();
                    resetForm.classList.add('shake');
                    setTimeout(() => {
                        resetForm.classList.remove('shake');
                    }, 500);
                    return;
                }
                
                const spinner = resetButton.querySelector('.spinner');
                const buttonText = resetButton.querySelector('span');
                
                // Show loading state
                spinner.style.display = 'block';
                buttonText.textContent = 'Resetting Password...';
                resetButton.classList.add('loading');
            });
            
            // Auto-focus on password field
            newPasswordInput.focus();
        });
    </script>
</body>
</html>