<?php
session_start();

// --- 1. Include Database Connection ---
// Assumes db_connection.php is located in the config folder
require_once 'config/db_connection.php'; 

$login_message = '';
$message_class = '';

// --- Handle Logout Redirection Status ---
if (isset($_GET['status']) && $_GET['status'] === 'logged_out') {
    $login_message = "You have logged out successfully.";
    $message_class = 'success';
}

// Redirect already logged-in users to the unified dashboard
if (isset($_SESSION['user_id'])) { 
    header("Location: admin_dashboard.php");
    exit();
}


// --- 2. Handle Secure Login Attempt (Database Check) ---
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';

    // Validate input and connection
    if (!isset($conn)) {
        $login_message = "Error: Database connection not established.";
        $message_class = 'error';
    } elseif (empty($username) || empty($password)) {
        $login_message = "Please enter both username and password.";
        $message_class = 'error';
    } else {
        // Prepare SQL statement to fetch user data and password hash
        // IMPORTANT: The 'role' column (e.g., 'Admin', 'HR') must be present in your 'users' table
        $sql = "SELECT user_id, username, password, role FROM users WHERE username = ?";
        
        if ($stmt = $conn->prepare($sql)) {
            $stmt->bind_param("s", $username);
            $stmt->execute();
            $result = $stmt->get_result();

            if ($result->num_rows === 1) {
                $user = $result->fetch_assoc();
                $stored_hash = $user['password'];

                // 3. Verify the plaintext password against the stored hash
                if (password_verify($password, $stored_hash)) {
                    // Successful login: Set session variables (including role)
                    $_SESSION['user_id'] = $user['user_id'];
                    $_SESSION['username'] = $user['username'];
                    $_SESSION['role'] = $user['role']; 
                    
                    // Redirect ALL users to the single dashboard
                    header("Location: admin_dashboard.php");
                    exit();

                } else {
                    $login_message = "Invalid credentials. Please try again.";
                    $message_class = 'error';
                }
            } else {
                $login_message = "Invalid credentials. Please try again.";
                $message_class = 'error';
            }
            $stmt->close();
        } else {
            $login_message = "Database error during login preparation: " . $conn->error;
            $message_class = 'error';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Login</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            background-color: #f7f9fb;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            height: 100vh;
            margin: 0;
        }
        .message {
            padding: 15px 25px;
            margin-bottom: 20px;
            border-radius: 8px;
            font-weight: bold;
            text-align: center;
            width: 90%;
            max-width: 400px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        }
        .message.success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .message.error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .login-container {
            background-color: #ffffff;
            padding: 40px;
            border-radius: 10px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 400px;
            text-align: center;
        }
        h1 {
            color: #2c3e50;
            margin-bottom: 30px;
            font-size: 28px;
        }
        label {
            display: block;
            text-align: left;
            margin-bottom: 5px;
            color: #34495e;
            font-weight: bold;
        }
        input[type="text"], input[type="password"] {
            width: 100%;
            padding: 12px;
            margin-bottom: 20px;
            border: 1px solid #e0e6ed;
            border-radius: 6px;
            box-sizing: border-box;
            transition: border-color 0.3s;
        }
        input[type="text"]:focus, input[type="password"]:focus {
            border-color: #3498db;
            outline: none;
        }
        button[type="submit"] {
            width: 100%;
            padding: 12px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s, transform 0.1s;
        }
        button[type="submit"]:hover {
            background-color: #2980b9;
        }
        button[type="submit"]:active {
            transform: translateY(1px);
        }
    </style>
</head>
<body>
    
    <?php if ($login_message): ?>
        <div class="message <?php echo $message_class; ?>">
            <?php echo htmlspecialchars($login_message); ?>
        </div>
    <?php endif; ?>

    <div class="login-container">
        <h1>User Login</h1>
        <form action="index.php" method="post">
            <label for="username">Username</label>
            <input type="text" name="username" id="username" required>

            <label for="password">Password</label>
            <input type="password" name="password" id="password" required>
            
            <button type="submit">Log In</button>
        </form>
    </div>
</body>
</html>
