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

<?php
// Check if role ID is provided
if (!isset($_GET['id']) || empty($_GET['id'])) {
    $_SESSION['error_message'] = "Role ID is required";
    header("Location: user_roles.php");
    exit();
}

$role_id = intval($_GET['id']);

// Get role details
$sql = "SELECT * FROM user_role WHERE role_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $role_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $_SESSION['error_message'] = "Role not found";
    header("Location: user_roles.php");
    exit();
}

$role = $result->fetch_assoc();

// Get current menu permissions
$menu_items_sql = "SELECT menu_item FROM menu_roles WHERE role_id = ?";
$menu_items_stmt = $conn->prepare($menu_items_sql);
$menu_items_stmt->bind_param("i", $role_id);
$menu_items_stmt->execute();
$menu_items_result = $menu_items_stmt->get_result();

$assigned_menu_items = [];
while ($row = $menu_items_result->fetch_assoc()) {
    $assigned_menu_items[] = $row['menu_item'];
}

// Get all available menu items
$all_menu_items_sql = "SELECT DISTINCT menu_item FROM menu_roles ORDER BY menu_item";
$all_menu_items_result = $conn->query($all_menu_items_sql);
$all_menu_items = [];

while ($row = $all_menu_items_result->fetch_assoc()) {
    $all_menu_items[] = $row['menu_item'];
}

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate role name
    $role_name = trim($_POST['role_name']);
    if (empty($role_name)) {
        $_SESSION['error_message'] = "Role name is required";
        header("Location: edit_role.php?id=" . $role_id);
        exit();
    }
    
    // Check if name already exists for other roles
    $check_sql = "SELECT COUNT(*) as count FROM user_role WHERE role_name = ? AND role_id != ?";
    $check_stmt = $conn->prepare($check_sql);
    $check_stmt->bind_param("si", $role_name, $role_id);
    $check_stmt->execute();
    $check_result = $check_stmt->get_result();
    $exists = $check_result->fetch_assoc()['count'] > 0;
    
    if ($exists) {
        $_SESSION['error_message'] = "Another role with this name already exists";
        header("Location: edit_role.php?id=" . $role_id);
        exit();
    }
    
    // Begin transaction
    $conn->begin_transaction();
    
    try {
        // Update role
        $update_sql = "UPDATE user_role SET role_name = ? WHERE role_id = ?";
        $update_stmt = $conn->prepare($update_sql);
        $update_stmt->bind_param("si", $role_name, $role_id);
        $update_stmt->execute();
        
        // Delete existing menu permissions
        $delete_sql = "DELETE FROM menu_roles WHERE role_id = ?";
        $delete_stmt = $conn->prepare($delete_sql);
        $delete_stmt->bind_param("i", $role_id);
        $delete_stmt->execute();
        
        // Add new menu permissions
        if (isset($_POST['menu_items']) && is_array($_POST['menu_items'])) {
            $menu_items = $_POST['menu_items'];
            $menu_sql = "INSERT INTO menu_roles (menu_item, role_id) VALUES (?, ?)";
            $menu_stmt = $conn->prepare($menu_sql);
            
            foreach ($menu_items as $menu_item) {
                $menu_stmt->bind_param("si", $menu_item, $role_id);
                $menu_stmt->execute();
            }
        }
        
        // Commit transaction
        $conn->commit();
        
        $_SESSION['success_message'] = "Role has been updated successfully";
        header("Location: view_role.php?id=" . $role_id);
        exit();
        
    } catch (Exception $e) {
        // Rollback on error
        $conn->rollback();
        $_SESSION['error_message'] = "Failed to update role: " . $e->getMessage();
        header("Location: edit_role.php?id=" . $role_id);
        exit();
    }
}
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Edit Role')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- Select2 CSS -->
    <link href="assets/libs/select2/css/select2.min.css" rel="stylesheet" type="text/css">
</head>

<body>
    <!-- Begin page -->
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Roles', 'title' => 'Edit Role')); ?>

                    <div class="row">
                        <div class="col-xl-12">
                            <div class="card">
                                <div class="card-header d-flex align-items-center">
                                    <h4 class="card-title mb-0 flex-grow-1">Edit Role Information</h4>
                                    <div>
                                        <a href="view_role.php?id=<?php echo $role_id; ?>" class="btn btn-light btn-sm">
                                            <i class="ri-eye-line align-bottom"></i> View Role
                                        </a>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <?php if (isset($_SESSION['error_message'])): ?>
                                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                            <strong>Error!</strong> <?php echo $_SESSION['error_message']; ?>
                                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                                        </div>
                                        <?php unset($_SESSION['error_message']); ?>
                                    <?php endif; ?>

                                    <form action="edit_role.php?id=<?php echo $role_id; ?>" method="POST">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="mb-3">
                                                    <label for="role_name" class="form-label">Role Name <span class="text-danger">*</span></label>
                                                    <input type="text" class="form-control" id="role_name" name="role_name" 
                                                           value="<?php echo htmlspecialchars($role['role_name']); ?>" required>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="mb-3">
                                                    <label class="form-label">Role ID</label>
                                                    <input type="text" class="form-control" value="<?php echo $role_id; ?>" readonly disabled>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="row mt-4">
                                            <div class="col-12">
                                                <h5 class="mb-3">Menu Permissions</h5>
                                                <div class="mb-3">
                                                    <label for="menu_items" class="form-label">Select Menu Items</label>
                                                    <select class="select2 form-control select2-multiple" id="menu_items" name="menu_items[]" multiple data-placeholder="Choose menu items...">
                                                        <?php foreach ($all_menu_items as $menu_item): ?>
                                                            <option value="<?php echo htmlspecialchars($menu_item); ?>" 
                                                                    <?php echo in_array($menu_item, $assigned_menu_items) ? 'selected' : ''; ?>>
                                                                <?php echo htmlspecialchars($menu_item); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                    <small class="form-text text-muted">
                                                        Select the menu items this role should have access to
                                                    </small>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="row mt-4">
                                            <div class="col-12">
                                                <div class="d-flex flex-wrap gap-2">
                                                    <button type="submit" class="btn btn-primary">
                                                        <i class="ri-save-line align-bottom me-1"></i> Update Role
                                                    </button>
                                                    <a href="view_role.php?id=<?php echo $role_id; ?>" class="btn btn-secondary">
                                                        <i class="ri-close-line align-bottom me-1"></i> Cancel
                                                    </a>
                                                </div>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- User Assignment Section -->
                    <div class="row">
                        <div class="col-xl-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Users with this Role</h4>
                                </div>
                                <div class="card-body">
                                    <?php
                                    // Get users with this role
                                    $users_sql = "SELECT user_id, username, full_name, email FROM users WHERE role_id = ? ORDER BY username";
                                    $users_stmt = $conn->prepare($users_sql);
                                    $users_stmt->bind_param("i", $role_id);
                                    $users_stmt->execute();
                                    $users_result = $users_stmt->get_result();
                                    ?>

                                    <?php if ($users_result->num_rows > 0): ?>
                                        <div class="table-responsive">
                                            <table class="table table-centered table-nowrap mb-0">
                                                <thead>
                                                    <tr>
                                                        <th>Username</th>
                                                        <th>Full Name</th>
                                                        <th>Email</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php while ($user = $users_result->fetch_assoc()): ?>
                                                        <tr>
                                                            <td><?php echo htmlspecialchars($user['username']); ?></td>
                                                            <td><?php echo htmlspecialchars($user['full_name']); ?></td>
                                                            <td><?php echo htmlspecialchars($user['email']); ?></td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    <?php else: ?>
                                        <div class="alert alert-info mb-0">
                                            <i class="ri-information-line me-2"></i>
                                            No users are currently assigned to this role.
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <!-- Select2 -->
    <script src="assets/libs/select2/js/select2.min.js"></script>
    
    <script src="assets/js/app.js"></script>
    
    <script>
        $(document).ready(function() {
            // Initialize Select2
            $(".select2").select2({
                width: '100%'
            });
            
            // Form validation
            $("form").on("submit", function(e) {
                const roleName = $("#role_name").val().trim();
                if (!roleName) {
                    e.preventDefault();
                    Swal.fire({
                        icon: 'error',
                        title: 'Validation Error',
                        text: 'Role name is required',
                        confirmButtonClass: 'btn btn-primary w-xs mt-2',
                        buttonsStyling: false
                    });
                    return false;
                }
                return true;
            });
        });
    </script>
</body>
</html>