<?php
// configp.php - Password Reset Configuration (SQLite Version)
// Place this in the same directory as forgot_password.php and reset_password.php

require_once __DIR__ . '/config.php';

// Function to request password reset (overrides the one in config.php if exists)
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.'];
        }
        
        // Check if reset_token column exists, if not add it
        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']]);
        
        // Also create password_resets table for better tracking
        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
        }
        
        // Send reset email
        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
        $resetLink = $protocol . $_SERVER['HTTP_HOST'] . dirname($_SERVER['SCRIPT_NAME']) . "/reset_password.php?token=" . $token;
        
        $subject = "Password Reset Request - " . APP_NAME;
        $message = "
        <html>
        <head>
            <title>Password Reset Request</title>
            <style>
                body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background: #06b6d4; color: white; padding: 20px; text-align: center; border-radius: 10px 10px 0 0; }
                .content { padding: 30px; background: #f9fafb; border: 1px solid #e5e7eb; border-top: none; border-radius: 0 0 10px 10px; }
                .button { display: inline-block; padding: 12px 24px; background: #06b6d4; color: white; text-decoration: none; border-radius: 6px; margin: 20px 0; font-weight: bold; }
                .footer { text-align: center; padding: 20px; font-size: 12px; color: #6b7280; }
                .warning { color: #dc2626; font-size: 12px; margin-top: 20px; padding: 10px; background: #fee2e2; border-radius: 5px; }
            </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 <strong>" . APP_NAME . "</strong> account.</p>
                    <p>Click the button below to reset your password:</p>
                    <p style='text-align: center;'>
                        <a href='{$resetLink}' class='button'>Reset Password</a>
                    </p>
                    <p>Or copy and paste this link into your browser:</p>
                    <p style='background: #f3f4f6; padding: 10px; border-radius: 5px; word-break: break-all;'>" . $resetLink . "</p>
                    <p><strong>This link will expire in 1 hour.</strong></p>
                    <div class='warning'>
                        ⚠️ If you did not request this password reset, please ignore this email and your password will remain unchanged.
                    </div>
                </div>
                <div class='footer'>
                    <p>This is an automated message from " . APP_NAME . ". Please do not reply to this email.</p>
                    <p>&copy; " . date('Y') . " " . APP_NAME . ". 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: " . APP_NAME . " <noreply@" . $_SERVER['HTTP_HOST'] . ">" . "\r\n";
        $headers .= "X-Mailer: PHP/" . phpversion();
        
        $mailSent = mail($email, $subject, $message, $headers);
        
        if ($mailSent) {
            // Log activity if function exists
            if (function_exists('logUserActivity')) {
                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.*, 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'],
                    'email' => $result['email']
                ];
            }
        } catch (Exception $e) {
            // Fallback to users table
        }
        
        // 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'],
                'email' => $user['email']
            ];
        }
        
        return ['valid' => false, 'message' => 'Invalid or expired reset token. Please request a new password reset.'];
        
    } catch(Exception $e) {
        error_log("Token validation error: " . $e->getMessage());
        return ['valid' => false, 'message' => 'An error occurred. Please try again.'];
    }
}

// Function to reset password
function resetPassword($token, $newPassword, $confirmPassword) {
    try {
        // Validate passwords match
        if ($newPassword !== $confirmPassword) {
            return ['success' => false, 'message' => 'Passwords do not match.'];
        }
        
        // 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. Please request a new password reset.'];
        }
        
        // 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
        if (function_exists('logUserActivity')) {
            logUserActivity($userId, 'password_reset', 'Password reset completed successfully');
        } else {
            // Manual log if function doesn't exist
            try {
                $stmt = $pdo->prepare("INSERT INTO user_activity (user_id, action, details, ip_address) VALUES (?, 'password_reset', 'Password reset completed', ?)");
                $stmt->execute([$userId, $_SERVER['REMOTE_ADDR'] ?? '']);
            } catch (Exception $e) {}
        }
        
        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.'];
    }
}
?>