<?php
define('SECURE_ACCESS', true);
require_once __DIR__ . '/config.php';
require_once 'includes/security_logger.php';

// Load google_oauth_config.php from join site
// JOIN_DOMAIN is already defined by shared tenant_loader.php
$join_dir = dirname(__DIR__) . '/' . parse_url(JOIN_URL, PHP_URL_HOST);
$possible_paths = [
    $join_dir . '/public_html/includes/google_oauth_config.php',
    '/mnt/apachehosted/zacdev/zackdevjoin.orkestrait.ai/public_html/includes/google_oauth_config.php',
];

$google_config_found = false;
foreach ($possible_paths as $path) {
    if (file_exists($path)) {
        require_once $path;
        $google_config_found = true;
        break;
    }
}

if (!$google_config_found) {
    $GOOGLE_OAUTH_ENABLED = false;
}


// Check if user is already logged in
if (isset($_SESSION['user_logged_in']) && $_SESSION['user_logged_in'] === true) {
    header('Location: dashboard.php');
    exit;
}

// Rate limiting - prevent brute force attacks
if (!isset($_SESSION['login_attempts'])) {
    $_SESSION['login_attempts'] = 0;
    $_SESSION['last_attempt_time'] = time();
}

// Reset attempts after 15 minutes
if (time() - $_SESSION['last_attempt_time'] > 900) {
    $_SESSION['login_attempts'] = 0;
}

// Block if too many attempts
if ($_SESSION['login_attempts'] >= 5) {
    $time_remaining = 900 - (time() - $_SESSION['last_attempt_time']);
    if ($time_remaining > 0) {
        $minutes = ceil($time_remaining / 60);
        $error = "Too many failed login attempts. Please try again in {$minutes} minute(s).";
        
        // Log blocked attempt
        try {
            $pdo_log = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
            $pdo_log->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            log_security_event($pdo_log, 'login_blocked', $_POST['username'] ?? 'unknown', "Blocked due to rate limiting. {$_SESSION['login_attempts']} attempts.");
            $pdo_log = null;
        } catch (PDOException $e) {
            // Silently fail if logging doesn't work
        }
    } else {
        $_SESSION['login_attempts'] = 0;
    }
}

// Handle login form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && (!isset($error))) {
    $username = trim($_POST['username']);
    $password = $_POST['password'];

    if (empty($username) || empty($password)) {
        $error = 'Please enter both username and password.';
    } else {
        try {
            $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            // Query for any user (admin or regular member)
            $stmt = $pdo->prepare("SELECT * FROM members WHERE username = ?");
            $stmt->execute([$username]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($user && password_verify($password, $user['password']) && !$user['suspended']) {
                // Check if email is verified (admins bypass this check)
                if (!$user['is_admin'] && !$user['email_verified']) {
                    $_SESSION['login_attempts']++;
                    $_SESSION['last_attempt_time'] = time();
                    log_security_event($pdo, 'login_failed', $username, "Email not verified");
                    $error = 'Please verify your email address before logging in. Check your inbox for the verification link or <a href="' . JOIN_DOMAIN . '/freejoin/resend.php?email=' . urlencode($user['email']) . '" style="color: var(--primary); text-decoration: underline;">resend verification email</a>.';
                } else {
                    // Update last access time and last login IP
                    $client_ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
                    $updateStmt = $pdo->prepare("UPDATE members SET last_access = NOW(), last_login_ip = ? WHERE id = ?");
                    $updateStmt->execute([$client_ip, $user['id']]);

                    // Determine user type for logging
                    $user_type = $user['is_admin'] ? 'admin' : 'member';
                    
                    // Log successful login
                    log_security_event($pdo, 'login_success', $username, "{$user_type} login successful");
                    
                    // Regenerate session ID to prevent session fixation
                    session_regenerate_id(true);
                    
                    // Reset login attempts on successful login
                    $_SESSION['login_attempts'] = 0;
                    
                    // Set session variables
                    $_SESSION['user_logged_in'] = true;
                    $_SESSION['username'] = $username;
                    $_SESSION['user_id'] = $user['id'];
                    $_SESSION['is_admin'] = (bool)$user['is_admin'];
                    $_SESSION['user_ip'] = $_SERVER['REMOTE_ADDR'];
                    $_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
                    $_SESSION['user_name'] = $user['firstName'] . ' ' . $user['lastName'];
                    $_SESSION['last_activity'] = time();

                    // Redirect to dashboard
                    header('Location: dashboard.php');
                    exit;
                }
            } elseif ($user && $user['suspended']) {
                $_SESSION['login_attempts']++;
                $_SESSION['last_attempt_time'] = time();
                log_security_event($pdo, 'login_failed', $username, "Account suspended");
                $error = 'Account suspended. Please contact an administrator.';
            } else {
                $_SESSION['login_attempts']++;
                $_SESSION['last_attempt_time'] = time();
                log_security_event($pdo, 'login_failed', $username, "Invalid credentials");
                $error = 'Invalid username or password.';
            }
        } catch (PDOException $e) {
            $error = 'Database connection error. Please try again later.';
        }
    }
}

// Generate Google OAuth state for CSRF protection
if (!isset($_SESSION['oauth_state'])) {
    $_SESSION['oauth_state'] = bin2hex(random_bytes(32));
}
$google_oauth_available = !empty($GOOGLE_OAUTH_ENABLED) && function_exists('getGoogleAuthUrl');
$google_auth_url = '';
if ($google_oauth_available) {
    $google_auth_url = getGoogleAuthUrl(GOOGLE_REDIRECT_LOGIN, $_SESSION['oauth_state']);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Member Login - <?php echo BRAND_NAME; ?></title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="/includes/css/login.css">
    <style>
        .oauth-divider {
            display: flex;
            align-items: center;
            gap: 15px;
            margin: 25px 0;
            color: #999;
            font-size: 0.9rem;
        }
        
        .oauth-divider::before,
        .oauth-divider::after {
            content: '';
            flex: 1;
            height: 1px;
            background: #e0e0e0;
        }
        
        .btn-google {
            width: 100%;
            padding: 12px 16px;
            background: white;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-weight: 600;
            font-size: 1rem;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            color: #333;
            text-decoration: none;
            margin-bottom: 20px;
        }
        
        .btn-google:hover {
            border-color: #4285f4;
            background: #f8f9fa;
            box-shadow: 0 2px 8px rgba(66, 133, 244, 0.2);
        }
        
        .btn-google svg {
            width: 20px;
            height: 20px;
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="login-card">
            <div class="logo">
                <div class="logo-text"><?php echo BRAND_NAME; ?></div>
                <div class="logo-subtitle">AI-Powered Fantasy Creation</div>
            </div>

            <h1 class="login-title">Welcome Back</h1>
            <p class="login-subtitle">Sign in to your account</p>

            <?php if (isset($error)): ?>
                <div class="error-message">
                    <?php echo $error; ?>
                </div>
            <?php endif; ?>

            <?php if ($google_oauth_available && $google_auth_url !== ''): ?>
            <!-- Google OAuth Button -->
            <a href="<?php echo htmlspecialchars($google_auth_url); ?>" class="btn-google">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4"/>
                    <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/>
                    <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05"/>
                    <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/>
                </svg>
                Sign in with Google
            </a>

            <div class="oauth-divider">or</div>
            <?php endif; ?>

            <form method="POST" action="">
                <div class="form-group">
                    <label class="form-label" for="username">Username</label>
                    <input
                        type="text"
                        id="username"
                        name="username"
                        class="form-input"
                        required
                        autocomplete="username"
                        placeholder="Enter your username"
                        value="<?php echo isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''; ?>"
                    >
                </div>

                <div class="form-group">
                    <label class="form-label" for="password">Password</label>
                    <input
                        type="password"
                        id="password"
                        name="password"
                        class="form-input"
                        required
                        autocomplete="current-password"
                        placeholder="Enter your password"
                    >
                </div>

                <button type="submit" class="login-btn">Sign In</button>
            </form>

            <div class="footer">
                <p>Forgot your password? <a href="forgot_password.php">Reset Password</a></p>
                <p style="margin-top: 1rem;">Don't Have An Account Yet? <a href="<?php echo JOIN_DOMAIN; ?>">Join Today</a></p>
            </div>
        </div>
    </div>
</body>
</html>
