<?php
require 'auth.php';
requireAdmin();
require 'db.php';
require 'vendor/autoload.php';

$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username   = $_POST['username'];
    $full_name  = $_POST['full_name'];
    $email      = $_POST['email'];
    $phone      = $_POST['phone'];
    $password   = password_hash($_POST['password'], PASSWORD_BCRYPT);
    $user_role  = $_POST['user_role'];
    $access_group = $_POST['access_group'] ?? '';

    // Generate 2FA secret
    //$ga = new PHPGangsta_GoogleAuthenticator();
    //$totp_secret = $ga->createSecret();

    $stmt = $pdo->prepare("INSERT INTO users (username, full_name, email, phone, password_hash, user_role, access_group)
                           VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([$username, $full_name, $email, $phone, $password, $user_role, $access_group]);

    $message = "User '$username' created successfully.";
}
?>

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

<div class="container mt-5">
    <h2>Add New User</h2>
    <?php if ($message): ?>
        <div class="alert alert-success"><?= htmlspecialchars($message) ?></div>
    <?php endif; ?>
    <form method="POST">
        <div class="mb-3">
            <label class="form-label">Username</label>
            <input type="text" name="username" required class="form-control">
        </div>
        <div class="mb-3">
            <label class="form-label">Full Name</label>
            <input type="text" name="full_name" required class="form-control">
        </div>
        <div class="mb-3">
            <label class="form-label">Email</label>
            <input type="email" name="email" required class="form-control">
        </div>
        <div class="mb-3">
            <label class="form-label">Phone</label>
            <input type="text" name="phone" class="form-control">
        </div>
        <div class="mb-3">
            <label class="form-label">Password</label>
            <input type="password" name="password" required class="form-control">
        </div>
        <div class="mb-3">
            <label class="form-label">Role</label>
            <select name="user_role" class="form-select" required>
                <option value="Admin">Admin</option>
                <option value="Operator">Operator</option>
                <option value="Installer">Installer</option>
                <option value="Client">Client</option>
            </select>
        </div>
        <div class="mb-3">
            <label class="form-label">Access Group</label>
            <input type="text" name="access_group" class="form-control">
        </div>
        <button type="button" class="btn btn-danger ms-2" onclick="history.back()">Cancel</button> <button type="submit" class="btn btn-primary">Create User</button>

    </form>
</div>


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