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

if (isLoggedIn()) {
    $redirect_url = '';
    switch ($_SESSION['user_type']) {
        case 'admin':
            $redirect_url = '../admin/dashboard.php';
            break;
        case 'company':
            $redirect_url = '../company/dashboard.php';
            break;
        case 'candidate':
            $redirect_url = '../candidate/dashboard.php';
            break;
    }
    redirect($redirect_url);
}

$error = '';
$success = '';

if (isset($_GET['message'])) {
    $success = $_GET['message'];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = sanitize($_POST['email']);
    $password = $_POST['password'];
    $user_type = $_POST['user_type'];
    
    if (empty($email) || empty($password) || empty($user_type)) {
        $error = 'All fields are required.';
    } else {
        // Initialize rate limiting
        $database = new Database();
        $db = $database->getConnection();
        $rateLimiter = new RateLimiter($db);
        $clientIP = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
        
        // Check rate limit
        if (!$rateLimiter->checkRateLimit($clientIP, 'login', 5, 900)) {
            $error = 'Too many login attempts. Please try again in 15 minutes.';
        }
        
        if (!$error) {
            $user = null;
            
            if ($user_type === 'admin') {
                $stmt = $db->prepare("SELECT * FROM admins WHERE email = ?");
                $stmt->execute([$email]);
                $user = $stmt->fetch();
                
                if ($user && password_verify($password, $user['password'])) {
                    $_SESSION['user_id'] = $user['id'];
                    $_SESSION['user_type'] = $user_type;
                    $_SESSION['user_email'] = $user['email'];
                    $_SESSION['username'] = $user['username'];
                }
            } elseif ($user_type === 'company') {
                // Look up company user and get company details
                $stmt = $db->prepare("
                    SELECT cu.*, c.name as company_name, c.status as company_status 
                    FROM company_users cu 
                    INNER JOIN companies c ON cu.company_id = c.id 
                    WHERE cu.email = ? AND cu.status = 'active'
                ");
                $stmt->execute([$email]);
                $user = $stmt->fetch();
                
                if ($user && password_verify($password, $user['password'])) {
                    if ($user['company_status'] !== 'approved') {
                        $error = 'Your company account is pending approval.';
                    } else {
                        $_SESSION['user_id'] = $user['id'];
                        $_SESSION['company_id'] = $user['company_id'];
                        $_SESSION['user_type'] = $user_type;
                        $_SESSION['user_email'] = $user['email'];
                        $_SESSION['company_name'] = $user['company_name'];
                        $_SESSION['user_name'] = $user['name'];
                        $_SESSION['is_primary_user'] = $user['is_primary'];
                    }
                }
            } elseif ($user_type === 'candidate') {
                $stmt = $db->prepare("SELECT * FROM candidates WHERE email = ?");
                $stmt->execute([$email]);
                $user = $stmt->fetch();
                
                if ($user && password_verify($password, $user['password'])) {
                    $_SESSION['user_id'] = $user['id'];
                    $_SESSION['user_type'] = $user_type;
                    $_SESSION['user_email'] = $user['email'];
                    $_SESSION['first_name'] = $user['first_name'];
                    $_SESSION['last_name'] = $user['last_name'];
                }
            }
            
            if ($user && !$error) {
                // Clear rate limiting on successful login
                $rateLimiter->clearAttempts($clientIP, 'login');
                
                // Regenerate session ID on login
                session_regenerate_id(true);
                
                $redirect_url = '';
                switch ($user_type) {
                    case 'admin':
                        $redirect_url = '../admin/dashboard.php';
                        break;
                    case 'company':
                        $redirect_url = '../company/dashboard.php';
                        break;
                    case 'candidate':
                        $redirect_url = '../candidate/dashboard.php';
                        break;
                }
                redirect($redirect_url);
            } else {
                // Record failed attempt
                $rateLimiter->recordAttempt($clientIP, 'login');
                
                if (!$error) {
                    $error = 'Invalid email or password.';
                }
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - <?php echo SITE_NAME; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body class="bg-light">
    <div class="container">
        <div class="row justify-content-center align-items-center min-vh-100">
            <div class="col-md-6 col-lg-5">
                <div class="card shadow">
                    <div class="card-body p-5">
                        <div class="text-center mb-4">
                            <h2 class="fw-bold text-primary">
                                <i class="fas fa-briefcase me-2"></i><?php echo SITE_NAME; ?>
                            </h2>
                            <p class="text-muted">Sign in to your account</p>
                        </div>
                        
                        <?php if ($error): ?>
                            <div class="alert alert-danger">
                                <i class="fas fa-exclamation-circle me-2"></i><?php echo $error; ?>
                            </div>
                        <?php endif; ?>
                        
                        <?php if ($success): ?>
                            <div class="alert alert-success">
                                <i class="fas fa-check-circle me-2"></i><?php echo $success; ?>
                            </div>
                        <?php endif; ?>
                        
                        <form method="POST">
                            <div class="mb-3">
                                <label for="user_type" class="form-label">Login As</label>
                                <select class="form-select" id="user_type" name="user_type" required>
                                    <option value="">Select user type</option>
                                    <option value="admin" <?php echo (isset($_POST['user_type']) && $_POST['user_type'] === 'admin') ? 'selected' : ''; ?>>Admin</option>
                                    <option value="company" <?php echo (isset($_POST['user_type']) && $_POST['user_type'] === 'company') ? 'selected' : ''; ?>>Company</option>
                                    <option value="candidate" <?php echo (isset($_POST['user_type']) && $_POST['user_type'] === 'candidate') ? 'selected' : ''; ?>>Job Seeker</option>
                                </select>
                            </div>
                            
                            <div class="mb-3">
                                <label for="email" class="form-label">Email Address</label>
                                <input type="email" class="form-control" id="email" name="email" 
                                       value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>" required>
                            </div>
                            
                            <div class="mb-3">
                                <label for="password" class="form-label">Password</label>
                                <input type="password" class="form-control" id="password" name="password" required>
                            </div>
                            
                            <button type="submit" class="btn btn-primary w-100 mb-3">
                                <i class="fas fa-sign-in-alt me-2"></i>Sign In
                            </button>
                        </form>
                        
                        <div class="text-center">
                            <p class="mb-0">Don't have an account? 
                                <a href="register.php" class="text-primary">Register here</a>
                            </p>
                            <a href="../index.php" class="text-muted">
                                <i class="fas fa-arrow-left me-1"></i>Back to Home
                            </a>
                        </div>
                        
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>