<?php
session_start();
include 'auth.php';
include 'config.php';

// Sirf admin access
if ($_SESSION['role'] != 'admin') {
    echo "Access Denied!";
    exit;
}

$error = "";
$success = "";

if (isset($_POST['create_user'])) {

    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $password = trim($_POST['password']);
    $role = $_POST['role'];

    // Check duplicate email
    $stmt = $conn->prepare("SELECT id FROM users WHERE email = :email");
    $stmt->bindParam(":email", $email);
    $stmt->execute();

    if ($stmt->rowCount() > 0) {
        $error = "Email already exists!";
    } else {

        $hashed_password = password_hash($password, PASSWORD_DEFAULT);

        $insert = $conn->prepare("
            INSERT INTO users (name, email, password, role)
            VALUES (:name, :email, :password, :role)
        ");

        $insert->bindParam(":name", $name);
        $insert->bindParam(":email", $email);
        $insert->bindParam(":password", $hashed_password);
        $insert->bindParam(":role", $role);

        if ($insert->execute()) {
            $success = "User Created Successfully!";
        } else {
            $error = "Something went wrong!";
        }
    }
}
?>

<h2>Add New User (Admin Only)</h2>

<?php if($error) echo "<p style='color:red;'>$error</p>"; ?>
<?php if($success) echo "<p style='color:green;'>$success</p>"; ?>

<form method="POST">
    <label>Name:</label><br>
    <input type="text" name="name" required><br><br>

    <label>Email:</label><br>
    <input type="email" name="email" required><br><br>

    <label>Password:</label><br>
    <input type="password" name="password" required><br><br>

    <label>Role:</label><br>
    <select name="role">
        <option value="user">User</option>
        <option value="accountant">Accountant</option>
        <option value="admin">Admin</option>
    </select><br><br>

    <button type="submit" name="create_user">Create User</button>
</form>
