<?php
session_start();
require '../includes/config.php';

// Restrict to admins
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header('Location: index.php');
    exit;
}

// Check if role_id is provided
if (!isset($_GET['role_id'])) {
    header('Location: manage_roles.php');
    exit;
}

$role_id = $_GET['role_id'];

// Fetch role details
$query = "SELECT role_name FROM roles WHERE role_id = ?";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, 'i', $role_id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$role = mysqli_fetch_assoc($result);

if (!$role) {
    header('Location: manage_roles.php');
    exit;
}

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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $role_name = trim($_POST['role_name']);
    
    if (empty($role_name)) {
        $error = "Role name is required.";
    } else {
        // Check if role_name is unique (excluding current role)
        $query = "SELECT role_id FROM roles WHERE role_name = ? AND role_id != ?";
        $stmt = mysqli_prepare($conn, $query);
        mysqli_stmt_bind_param($stmt, 'si', $role_name, $role_id);
        mysqli_stmt_execute($stmt);
        if (mysqli_stmt_get_result($stmt)->num_rows > 0) {
            $error = "Role name already exists.";
        } else {
            $query = "UPDATE roles SET role_name = ? WHERE role_id = ?";
            $stmt = mysqli_prepare($conn, $query);
            mysqli_stmt_bind_param($stmt, 'si', $role_name, $role_id);
            if (mysqli_stmt_execute($stmt)) {
                $success = "Role updated successfully.";
            } else {
                $error = "Failed to update role: " . mysqli_error($conn);
            }
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Edit Role</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="../css/style.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <h2>Edit Role</h2>
        <?php if ($success): ?>
            <div class="alert alert-success"><?php echo htmlspecialchars($success); ?></div>
        <?php endif; ?>
        <?php if ($error): ?>
            <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>

        <form method="POST">
            <div class="form-group mb-3">
                <label>Role Name</label>
                <input type="text" name="role_name" class="form-control" value="<?php echo htmlspecialchars($role['role_name']); ?>" required>
            </div>
            <button type="submit" class="btn btn-primary">Update Role</button>
            <a href="manage_roles.php" class="btn btn-secondary">Back to Manage Roles</a>
        </form>
    </div>
</body>
</html>