<?php
// member/forgot_password.php
require_once '../config.php';

// ============================================
// Password Reset Functions (SQLite version)
// ============================================

// Function to request password reset
function requestPasswordReset($email) {
    try {
        $pdo = getDBConnection();
        
        // Check if user exists
        $stmt = $pdo->prepare("SELECT id, username, email FROM users WHERE email = ?");
        $stmt->execute([$email]);
        $user = $stmt->fetch();
        
        if (!$user) {
            // For security, don't reveal if email exists
            return ['success' => true, 'message' => 'If an account exists with this email, you will receive a password reset link.'];
        }
        
        // Ensure reset_token and reset_expires columns exist
        try {
            $pdo->exec("ALTER TABLE users ADD COLUMN reset_token TEXT");
            $pdo->exec("ALTER TABLE users ADD COLUMN reset_expires DATETIME");
        } catch (Exception $e) {
            // Columns already exist
        }
        
        // Generate unique reset token
        $token = bin2hex(random_bytes(32));
        $expires = date('Y-m-d H:i:s', strtotime('+1 hour'));
        
        // Store token in users table
        $stmt = $pdo->prepare("UPDATE users SET reset_token = ?, reset_expires = ? WHERE id = ?");
        $stmt->execute([$token, $expires, $user['id']]);
        
        // Create password_resets table if not exists
        try {
            $pdo->exec("CREATE TABLE IF NOT EXISTS password_resets (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_id INTEGER NOT NULL,
                token TEXT NOT NULL UNIQUE,
                expires_at DATETIME NOT NULL,
                used INTEGER DEFAULT 0,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
            )");
            
            // Insert into password_resets table
            $stmt = $pdo->prepare("INSERT INTO password_resets (user_id, token, expires_at) VALUES (?, ?, ?)");
            $stmt->execute([$user['id'], $token, $expires]);
        } catch (Exception $e) {
            // Table might already exist
        }
        
        // Build reset link
        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
        $resetLink = $protocol . $_SERVER['HTTP_HOST'] . dirname($_SERVER['SCRIPT_NAME']) . "/forgot_password.php?token=" . $token;
        
        // Send email
        $subject = "Password Reset Request - Soul Guard";
        $message = "
        <html>
        <head>
            <title>Password Reset Request</title>
            <style>
                body { font-family: Arial, sans-serif; line-height: 1.6; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background: #06b6d4; color: white; padding: 20px; text-align: center; }
                .content { padding: 30px; background: #f9fafb; }
                .button { display: inline-block; padding: 12px 24px; background: #06b6d4; color: white; text-decoration: none; border-radius: 6px; }
                .footer { text-align: center; padding: 20px; font-size: 12px; color: #6b7280; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h2>Password Reset Request</h2>
                </div>
                <div class='content'>
                    <p>Hello <strong>" . htmlspecialchars($user['username']) . "</strong>,</p>
                    <p>We received a request to reset your password for your Soul Guard account.</p>
                    <p style='text-align: center;'>
                        <a href='{$resetLink}' class='button'>Reset Password</a>
                    </p>
                    <p>Or copy and paste this link: <br>{$resetLink}</p>
                    <p><strong>This link will expire in 1 hour.</strong></p>
                    <p>If you did not request this, please ignore this email.</p>
                </div>
                <div class='footer'>
                    <p>© " . date('Y') . " Soul Guard. All rights reserved.</p>
                </div>
            </div>
        </body>
        </html>
        ";
        
        $headers = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
        $headers .= "From: Soul Guard <noreply@" . $_SERVER['HTTP_HOST'] . ">" . "\r\n";
        
        $mailSent = @mail($email, $subject, $message, $headers);
        
        if ($mailSent) {
            logUserActivity($user['id'], 'password_reset_request', 'Password reset requested');
            return ['success' => true, 'message' => 'Password reset link has been sent to your email address.'];
        } else {
            error_log("Failed to send password reset email to: " . $email);
            return ['success' => false, 'message' => 'Failed to send email. Please try again or contact support.'];
        }
        
    } catch(Exception $e) {
        error_log("Password reset error: " . $e->getMessage());
        return ['success' => false, 'message' => 'An error occurred. Please try again later.'];
    }
}

// Function to validate reset token
function validateResetToken($token) {
    try {
        $pdo = getDBConnection();
        
        // First check password_resets table
        try {
            $stmt = $pdo->prepare("
                SELECT pr.user_id, u.username, u.email 
                FROM password_resets pr
                JOIN users u ON pr.user_id = u.id
                WHERE pr.token = ? AND pr.expires_at > datetime('now') AND pr.used = 0
            ");
            $stmt->execute([$token]);
            $result = $stmt->fetch();
            
            if ($result) {
                return ['valid' => true, 'user_id' => $result['user_id'], 'username' => $result['username']];
            }
        } catch (Exception $e) {}
        
        // Check users table for token
        $stmt = $pdo->prepare("
            SELECT id, username, email 
            FROM users 
            WHERE reset_token = ? AND reset_expires > datetime('now')
        ");
        $stmt->execute([$token]);
        $user = $stmt->fetch();
        
        if ($user) {
            return ['valid' => true, 'user_id' => $user['id'], 'username' => $user['username']];
        }
        
        return ['valid' => false, 'message' => 'Invalid or expired reset token.'];
        
    } catch(Exception $e) {
        error_log("Token validation error: " . $e->getMessage());
        return ['valid' => false, 'message' => 'An error occurred.'];
    }
}

// Function to reset password
function resetPassword($token, $newPassword) {
    try {
        // Validate password strength
        if (strlen($newPassword) < 8) {
            return ['success' => false, 'message' => 'Password must be at least 8 characters long.'];
        }
        
        if (!preg_match('/[A-Z]/', $newPassword)) {
            return ['success' => false, 'message' => 'Password must contain at least one uppercase letter.'];
        }
        
        if (!preg_match('/[a-z]/', $newPassword)) {
            return ['success' => false, 'message' => 'Password must contain at least one lowercase letter.'];
        }
        
        if (!preg_match('/[0-9]/', $newPassword)) {
            return ['success' => false, 'message' => 'Password must contain at least one number.'];
        }
        
        $pdo = getDBConnection();
        $userId = null;
        
        // First check password_resets table
        try {
            $stmt = $pdo->prepare("SELECT user_id FROM password_resets WHERE token = ? AND expires_at > datetime('now') AND used = 0");
            $stmt->execute([$token]);
            $reset = $stmt->fetch();
            
            if ($reset) {
                $userId = $reset['user_id'];
                // Mark token as used
                $stmt = $pdo->prepare("UPDATE password_resets SET used = 1 WHERE token = ?");
                $stmt->execute([$token]);
            }
        } catch (Exception $e) {}
        
        // If not found in password_resets, check users table
        if (!$userId) {
            $stmt = $pdo->prepare("SELECT id FROM users WHERE reset_token = ? AND reset_expires > datetime('now')");
            $stmt->execute([$token]);
            $user = $stmt->fetch();
            
            if ($user) {
                $userId = $user['id'];
            }
        }
        
        if (!$userId) {
            return ['success' => false, 'message' => 'Invalid or expired reset token.'];
        }
        
        // Hash the new password
        $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
        
        // Update user password
        $stmt = $pdo->prepare("UPDATE users SET password_hash = ?, reset_token = NULL, reset_expires = NULL WHERE id = ?");
        $stmt->execute([$hashedPassword, $userId]);
        
        // Log the password change
        logUserActivity($userId, 'password_reset', 'Password reset completed successfully');
        
        return ['success' => true, 'message' => 'Password has been reset successfully. You can now login with your new password.'];
        
    } catch(Exception $e) {
        error_log("Password reset error: " . $e->getMessage());
        return ['success' => false, 'message' => 'An error occurred. Please try again.'];
    }
}

// ============================================
// Main Script Logic
// ============================================

$error = '';
$success = '';
$resetMode = false;
$token = $_GET['token'] ?? '';

// Validate token if provided
if ($token) {
    $validation = validateResetToken($token);
    if ($validation['valid']) {
        $resetMode = true;
        $validToken = true;
    } else {
        $error = $validation['message'];
        $resetMode = false;
    }
}

// Handle password reset submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reset_password'])) {
    $token = $_POST['token'] ?? '';
    $password = $_POST['password'] ?? '';
    $confirm = $_POST['confirm_password'] ?? '';
    
    if (strlen($password) < 8) {
        $error = 'Password must be at least 8 characters';
    } elseif ($password !== $confirm) {
        $error = 'Passwords do not match';
    } else {
        $result = resetPassword($token, $password);
        if ($result['success']) {
            $success = $result['message'];
            $resetMode = false;
        } else {
            $error = $result['message'];
            // Re-validate token to show form again
            $validation = validateResetToken($token);
            if ($validation['valid']) {
                $resetMode = true;
            }
        }
    }
}

// Handle forgot password request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['request_reset'])) {
    $email = trim($_POST['email'] ?? '');
    
    if (empty($email)) {
        $error = 'Please enter your email address';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'Please enter a valid email address';
    } else {
        $result = requestPasswordReset($email);
        if ($result['success']) {
            $success = $result['message'];
        } else {
            $error = $result['message'];
        }
    }
}

$theme = getTheme();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Forgot Password - Soul Guard</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
        }
        
        body.dark {
            background: linear-gradient(135deg, #0a0a0f 0%, #1a1a2e 100%);
            color: #e4e4e7;
        }
        
        body.light {
            background: linear-gradient(135deg, #f5f5f5 0%, #e8e8e8 100%);
            color: #1a1a2e;
        }
        
        .container {
            width: 100%;
            max-width: 450px;
            padding: 20px;
        }
        
        .card {
            background: rgba(255, 255, 255, 0.05);
            border-radius: 20px;
            padding: 40px;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        body.light .card {
            background: rgba(255, 255, 255, 0.9);
            border: 1px solid rgba(0, 0, 0, 0.1);
        }
        
        .logo {
            text-align: center;
            margin-bottom: 30px;
        }
        
        .logo h1 {
            font-size: 32px;
            background: linear-gradient(135deg, #06b6d4, #14b8a6);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        label {
            display: block;
            margin-bottom: 8px;
            font-size: 14px;
            font-weight: 500;
        }
        
        input {
            width: 100%;
            padding: 12px 16px;
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 10px;
            color: inherit;
            font-size: 14px;
            transition: all 0.3s;
        }
        
        body.light input {
            background: #fff;
            border: 1px solid #ddd;
            color: #1a1a2e;
        }
        
        input:focus {
            outline: none;
            border-color: #06b6d4;
        }
        
        button {
            width: 100%;
            padding: 14px;
            background: linear-gradient(135deg, #06b6d4, #14b8a6);
            border: none;
            border-radius: 10px;
            color: white;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s, box-shadow 0.2s;
        }
        
        button:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 20px rgba(6, 182, 212, 0.3);
        }
        
        .links {
            text-align: center;
            margin-top: 20px;
            font-size: 14px;
        }
        
        .links a {
            color: #06b6d4;
            text-decoration: none;
        }
        
        .links a:hover {
            text-decoration: underline;
        }
        
        .error {
            background: rgba(239, 68, 68, 0.2);
            border: 1px solid rgba(239, 68, 68, 0.3);
            color: #ef4444;
            padding: 12px;
            border-radius: 10px;
            margin-bottom: 20px;
            font-size: 14px;
        }
        
        .success {
            background: rgba(34, 197, 94, 0.2);
            border: 1px solid rgba(34, 197, 94, 0.3);
            color: #22c55e;
            padding: 12px;
            border-radius: 10px;
            margin-bottom: 20px;
            font-size: 14px;
        }
        
        .theme-toggle {
            position: fixed;
            top: 20px;
            right: 20px;
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 50%;
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            font-size: 20px;
            transition: all 0.3s;
        }
        
        .theme-toggle:hover {
            transform: scale(1.1);
        }
        
        .info-text {
            text-align: center;
            font-size: 12px;
            color: #6b7280;
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        body.light .info-text {
            border-top-color: rgba(0, 0, 0, 0.1);
        }
        
        .password-strength {
            margin-top: 8px;
            font-size: 11px;
        }
        
        .password-strength.weak { color: #ef4444; }
        .password-strength.medium { color: #f59e0b; }
        .password-strength.strong { color: #22c55e; }
    </style>
</head>
<body class="<?php echo $theme; ?>">
    <div class="theme-toggle" onclick="toggleTheme()">
        <?php echo $theme === 'dark' ? '☀️' : '🌙'; ?>
    </div>
    
    <div class="container">
        <div class="card">
            <div class="logo">
                <h1>🛡️ Soul Guard</h1>
                <p><?php echo $resetMode ? 'Reset Your Password' : 'Forgot Password'; ?></p>
            </div>
            
            <?php if ($error): ?>
                <div class="error"><?php echo htmlspecialchars($error); ?></div>
            <?php endif; ?>
            
            <?php if ($success): ?>
                <div class="success"><?php echo htmlspecialchars($success); ?></div>
                <div class="links">
                    <a href="login.php">← Return to Login</a>
                </div>
            <?php elseif ($resetMode): ?>
                <form method="POST" action="">
                    <input type="hidden" name="token" value="<?php echo htmlspecialchars($token); ?>">
                    <input type="hidden" name="reset_password" value="1">
                    
                    <div class="form-group">
                        <label>New Password</label>
                        <input type="password" name="password" id="password" required placeholder="Min 8 characters" onkeyup="checkStrength()">
                        <div class="password-strength" id="strength"></div>
                    </div>
                    
                    <div class="form-group">
                        <label>Confirm Password</label>
                        <input type="password" name="confirm_password" required placeholder="Confirm your password">
                    </div>
                    
                    <button type="submit">Reset Password</button>
                </form>
                
                <div class="info-text">
                    Password must be at least 8 characters and contain uppercase, lowercase, and numbers.
                </div>
            <?php else: ?>
                <form method="POST" action="">
                    <input type="hidden" name="request_reset" value="1">
                    
                    <div class="form-group">
                        <label>Email Address</label>
                        <input type="email" name="email" required placeholder="your@email.com" autofocus>
                    </div>
                    
                    <button type="submit">Send Reset Link</button>
                </form>
                
                <div class="info-text">
                    Enter your email address and we'll send you a link to reset your password.
                </div>
            <?php endif; ?>
            
            <div class="links">
                <a href="login.php">← Back to Login</a>
                <?php if (!$resetMode && !$success): ?>
                | <a href="register.php">Create Account</a>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <script>
        function toggleTheme() {
            const body = document.body;
            const isDark = body.classList.contains('dark');
            const newTheme = isDark ? 'light' : 'dark';
            
            body.classList.remove('dark', 'light');
            body.classList.add(newTheme);
            
            document.cookie = `soulguard_theme=${newTheme}; path=/; max-age=31536000`;
            
            const btn = document.querySelector('.theme-toggle');
            btn.innerHTML = newTheme === 'dark' ? '☀️' : '🌙';
        }
        
        function checkStrength() {
            const password = document.getElementById('password').value;
            const strengthDiv = document.getElementById('strength');
            
            if (password.length === 0) {
                strengthDiv.innerHTML = '';
                return;
            }
            
            let strength = 0;
            let message = '';
            let className = '';
            
            if (password.length >= 8) strength++;
            if (password.match(/[A-Z]/)) strength++;
            if (password.match(/[a-z]/)) strength++;
            if (password.match(/[0-9]/)) strength++;
            if (password.match(/[^A-Za-z0-9]/)) strength++;
            
            if (strength <= 2) {
                message = 'Weak password';
                className = 'weak';
            } else if (strength <= 4) {
                message = 'Medium password';
                className = 'medium';
            } else {
                message = 'Strong password';
                className = 'strong';
            }
            
            strengthDiv.innerHTML = message;
            strengthDiv.className = 'password-strength ' + className;
        }
    </script>
</body>
</html>