<?php
if(!isset($_SESSION)) { session_start(); }

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $user_type = $_POST['user_type'] ?? '';
    
    // Validate input
    if (empty($username) || empty($password) || empty($user_type)) {
        header("Location: /v2/login.php?error=missing_fields");
        exit;
    }
    
    // Validate user type
    if (!in_array($user_type, ['admin', 'judge'])) {
        header("Location: /v2/login.php?error=invalid_user_type");
        exit;
    }
    
    // Database connection
    include '../includes/db.php';
    
    try {
        // Query to find user with matching username and role from users table
        $stmt = $pdo->prepare("SELECT id, username, password, role, judge_id FROM users WHERE username = ? AND role = ?");
        $stmt->execute([$username, $user_type]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($user && $password === $user['password']) {
            // Successful login - set session variables
            $_SESSION['user_logged_in'] = true;
            $_SESSION['user_type'] = $user['role'];
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['user_name'] = $user['username'];
            
            // Store judge_id if user is a judge
            if ($user['role'] === 'judge' && $user['judge_id']) {
                $_SESSION['judge_id'] = $user['judge_id'];
            }
            
            // Backward compatibility session variables
            if ($user['role'] === 'admin') {
                $_SESSION['admin_logged_in'] = true;
                $_SESSION['judge_id'] = $user['id'];
            } elseif ($user['role'] === 'judge') {
                $_SESSION['judge_logged_in'] = true;
            }
            
            // Log successful login (optional)
            error_log("Successful login: User {$user['username']} ({$user['role']}) from IP: " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
            
            // Redirect to appropriate dashboard
            if ($user['role'] === 'admin') {
                header("Location: /v2/admin/dashboard.php");
            } elseif ($user['role'] === 'judge') {
                header("Location: /v2/judge/dashboard.php");
            }
            exit;
        } else {
            // Invalid credentials - log the attempt
            error_log("Failed login: Username '{$username}', Role '{$user_type}' from IP: " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
            header("Location: /v2/login.php?error=invalid_credentials");
            exit;
        }
        
    } catch(PDOException $e) {
        error_log("Database error during login: " . $e->getMessage());
        header("Location: /v2/login.php?error=system_error");
        exit;
    }
} else {
    // Not a POST request - redirect to login
    header("Location: /v2/login.php");
    exit;
}
?>