<?php
include 'layouts/session.php';
include 'layouts/dbconn.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $role_name = trim($_POST['role_name']);

    // Validate input
    if (empty($role_name)) {
        $_SESSION['error'] = "Role name is required";
        header("Location: add_role.php");
        exit();
    }

    try {
        // Get the next role_id
        $stmt = $conn->prepare("SELECT MAX(role_id) as max_id FROM user_role");
        $stmt->execute();
        $result = $stmt->get_result();
        $row = $result->fetch_assoc();
        $new_role_id = ($row['max_id'] ?? 0) + 1;

        // Insert the new role
        $stmt = $conn->prepare("INSERT INTO user_role (role_id, role_name) VALUES (?, ?)");
        $stmt->bind_param("is", $new_role_id, $role_name);

        if ($stmt->execute()) {
            $_SESSION['success'] = "Role created successfully";
            header("Location: all_roles.php");
            exit();
        } else {
            throw new Exception($stmt->error);
        }
    } catch (Exception $e) {
        $_SESSION['error'] = "Error creating role: " . $e->getMessage();
        header("Location: add_role.php");
        exit();
    }
} else {
    header("Location: add_role.php");
    exit();
}
?>