<?php
// Start a new session or resume the existing one
session_start();

// Include the database connection file. This populates $pdo and $error_message.
require_once 'db_connect.php';

// Check if the login form was submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST' && empty($error_message)) {
    $username = trim($_POST['username']);
    $password = $_POST['password'];

    // SQL query to fetch the user by username
    $sql = 'SELECT * FROM users WHERE username = ?';
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$username]);
    $user = $stmt->fetch();

    if ($user) {
        // Verify the submitted password against the hashed password in the database
        // NOTE: md5 is generally insecure for password storage. Consider using password_hash() and password_verify() for new development.
        if (md5($password) === $user['password']) {

            // Authentication successful!
            // Set basic session variables
            $_SESSION['loggedin'] = true;
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            // ADD THIS LINE (Make sure 'name' matches your database column name) 122625
            $_SESSION['full_name'] = $user['name'];

            // Fetch all hubs assigned to this user
            $sql_hubs = "SELECT hub FROM hub_supervisors WHERE username = ?";
            $stmt_hubs = $pdo->prepare($sql_hubs);
            $stmt_hubs->execute([$user['username']]);
            $hubs = $stmt_hubs->fetchAll(PDO::FETCH_COLUMN, 0);

            // Check if any hubs were found
            if ($hubs) {
                // Store the array of hubs in a session variable
                $_SESSION['hubs_assigned'] = $hubs;
            } else {
                // Handle the case where the user is not assigned to any hubs
                $_SESSION['hubs_assigned'] = [];
            }
            
            // Assuming you have a 'coor_admin' field in your 'users' table or a similar lookup
            // If the user has coor_admin flag set in the DB, set it in the session
            // NOTE: I am adding this based on your all_employees.php file which uses $_SESSION['coor_admin']
            $_SESSION['coor_admin'] = $user['coor_admin'] ?? 0;


            // --- NEW DEVICE DETECTION LOGIC ---
            $user_agent = $_SERVER['HTTP_USER_AGENT'];
            $mobile_agents = '/(android|ip(hone|od|ad)|windows phone|blackberry|mobile|opera mini)/i';

            if (preg_match($mobile_agents, $user_agent)) {
                // Mobile or Tablet device detected
                header('Location: ca_reports.php'); // Redirect to your mobile file
            } else {
                // Desktop/Laptop device detected
                header('Location: ca_reports.php'); // Redirect to your desktop file
            }
            // --- END NEW LOGIC ---

            exit;
        } else {
            // Incorrect password
            $error_message = "Invalid username or password.";
        }
    } else {
        // User not found
        $error_message = "Invalid username or password.";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RGServe Login</title>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="css/login_style.css">
</head>
<body>
    <div class="background-animation"></div>
    <div class="login-container">
        <img src="images/logo.png" alt="RGServe Logo" class="logo">
        <?php if (!empty($error_message)): ?>
            <p style="color: red; font-weight: bold;"><?php echo htmlspecialchars($error_message); ?></p>
        <?php endif; ?>
        <form action="login.php" method="POST">
            <div class="input-group">
                <label for="username">Username</label>
                <input type="text" id="username" name="username" placeholder="Enter your username" required>
            </div>
            <div class="input-group">
                <label for="password">Password</label>
                <input type="password" id="password" name="password" placeholder="Enter your password" required>
            </div>
            <button type="submit" class="btn-login">Login</button>
            <div class="forgot-password">
                <a href="#">Forgot Password?</a>
            </div>
            <div class="signup-link">
                Don't have an account? <a href="#">Sign Up</a>
            </div>
        </form>
    </div>
</body>
</html>