<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    include 'layouts/dbconn.php';
    
    $username = $_POST['username'];
    $password = $_POST['password'];
    
    // Modified query to also get the role information
    $sql = "SELECT u.*, ur.role_id 
            FROM users u 
            LEFT JOIN user_roles ur ON u.user_id = ur.user_id 
            WHERE u.username = ?";
            
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $user = $result->fetch_assoc();
        if (password_verify($password, $user['password'])) {
            // Store user information in session
            $_SESSION['user_id'] = $user['user_id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['role_id'] = $user['role_id']; // This will now be the numeric role_id
            $_SESSION['user_role'] = $user['user_role']; // Store the text role as well if needed
            
            // Update last active time
            $update_sql = "UPDATE users SET last_active = NOW() WHERE user_id = ?";
            $update_stmt = $conn->prepare($update_sql);
            $update_stmt->bind_param("i", $user['user_id']);
            $update_stmt->execute();
            $update_stmt->close();

            echo json_encode(array(
                'success' => true, 
                'role_id' => $user['role_id']
            ));
        } else {
            echo json_encode(array(
                'success' => false, 
                'message' => 'Invalid username or password'
            ));
        }
    } else {
        echo json_encode(array(
            'success' => false, 
            'message' => 'Invalid username or password'
        ));
    }
    
    $stmt->close();
    $conn->close();
}
?>