<?php
session_start();
include "db.php";

$error = '';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $office_name = trim($_POST['office_name']);
    $password = $_POST['password'];

    if (empty($office_name) || empty($password)) {
        $error = "Please enter both office name and password.";
    } else {
        $stmt = $conn->prepare("SELECT staff_id, email FROM staff WHERE office_name = ? AND password = ?");
        $stmt->bind_param("ss", $office_name, $password);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows === 1) {
            $user = $result->fetch_assoc();
            $_SESSION['user_id'] = $user['staff_id'];  // store staff_id here
            $_SESSION['office_name'] = $office_name;
            $_SESSION['email'] = $user['email'];
            header("Location: dashboard.php");
            exit;
        } else {
            $error = "Invalid office name or password.";
        }
        $stmt->close();
    }
}
?>

<?php include "header.php"; ?>

<div class="container mt-5" style="max-width: 400px;">
    <h2 class="mb-4 text-center">Staff Login</h2>

    <?php if ($error): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <form method="post" novalidate>
        <div class="mb-3">
            <label for="office_name" class="form-label">Office Name</label>
            <input type="text" class="form-control" id="office_name" name="office_name" required value="<?= isset($_POST['office_name']) ? htmlspecialchars($_POST['office_name']) : '' ?>">
        </div>
        <div class="mb-3">
            <label for="password" class="form-label">Password</label>
            <input type="password" class="form-control" id="password" name="password" required minlength="6">
        </div>
        <button type="submit" class="btn btn-primary w-100">Login</button>
    </form>
</div>

<?php include "footer.php"; ?>
