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

$error = '';
$success = '';

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

    if (empty($office_name) || empty($password) || empty($confirm_password)) {
        $error = "All fields are required.";
    } elseif ($password !== $confirm_password) {
        $error = "Passwords do not match.";
    } else {
        // Check if office already exists
        $stmt = $conn->prepare("SELECT staff_id FROM staff WHERE office_name = ?");
        $stmt->bind_param("s", $office_name);
        $stmt->execute();
        $stmt->store_result();

        if ($stmt->num_rows > 0) {
            $error = "Office name already registered.";
        } else {
            // Insert without password hashing
            $stmt = $conn->prepare("INSERT INTO staff (office_name, password) VALUES (?, ?)");
            $stmt->bind_param("ss", $office_name, $password);

            if ($stmt->execute()) {
                $success = "Registration successful! You can now <a href='login.php'>login</a>.";
            } else {
                $error = "Database error: " . $conn->error;
            }
        }
        $stmt->close();
    }
}
?>

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

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

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

    <?php if ($success): ?>
        <div class="alert alert-success"><?= $success ?></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 (min 6 chars)</label>
            <input type="password" class="form-control" id="password" name="password" 
                   required minlength="6">
        </div>
        <div class="mb-3">
            <label for="confirm_password" class="form-label">Confirm Password</label>
            <input type="password" class="form-control" id="confirm_password" 
                   name="confirm_password" required minlength="6">
        </div>
        <button type="submit" class="btn btn-primary w-100">Register</button>
    </form>
</div>

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