<?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 menu permissions for this role
$menu_sql = "SELECT * FROM menu_roles WHERE role_id = ?";
$menu_stmt = $conn->prepare($menu_sql);
$menu_stmt->bind_param("i", $role_id);
$menu_stmt->execute();
$menu_result = $menu_stmt->get_result();
$menu_permissions = [];

while ($row = $menu_result->fetch_assoc()) {
    $menu_permissions[] = $row;
}

// Get users with this role
$users_sql = "SELECT u.user_id, u.username, u.full_name, u.email, u.created_at, u.last_active 
             FROM users u 
             WHERE u.role_id = ?";
$users_stmt = $conn->prepare($users_sql);
$users_stmt->bind_param("i", $role_id);
$users_stmt->execute();
$users_result = $users_stmt->get_result();
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'View Role')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- DataTables -->
    <link href="assets/libs/datatables.net-bs4/css/dataTables.bootstrap4.min.css" rel="stylesheet" type="text/css">
    <link href="assets/libs/datatables.net-responsive-bs4/css/responsive.bootstrap4.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' => 'View Role Details')); ?>

                    <div class="row">
                        <div class="col-xl-4">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Role Information</h4>
                                </div>
                                <div class="card-body">
                                    <div class="text-center mb-4">
                                        <div class="avatar-lg mx-auto mb-3">
                                            <div class="avatar-title bg-soft-primary text-primary display-5 rounded-circle">
                                                <i class="ri-shield-user-line"></i>
                                            </div>
                                        </div>
                                        <h5 class="font-size-16 mb-1"><?php echo htmlspecialchars($role['role_name']); ?></h5>
                                        <p class="text-muted">Role ID: <?php echo $role['role_id']; ?></p>
                                    </div>

                                    <div class="mt-4">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="mb-4">
                                                    <h5 class="font-size-13 text-uppercase text-muted">Created Date:</h5>
                                                    <p class="mb-0"><?php echo isset($role['created_at']) ? date('d M Y', strtotime($role['created_at'])) : 'N/A'; ?></p>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="mb-4">
                                                    <h5 class="font-size-13 text-uppercase text-muted">Status:</h5>
                                                    <?php 
                                                    // Check if role has users
                                                    $user_count_sql = "SELECT COUNT(*) as count FROM users WHERE role_id = ?";
                                                    $user_count_stmt = $conn->prepare($user_count_sql);
                                                    $user_count_stmt->bind_param("i", $role_id);
                                                    $user_count_stmt->execute();
                                                    $user_count_result = $user_count_stmt->get_result();
                                                    $user_count = $user_count_result->fetch_assoc()['count'];
                                                    
                                                    $status_class = $user_count > 0 ? 'bg-success' : 'bg-warning';
                                                    $status_text = $user_count > 0 ? 'Active' : 'Unused';
                                                    ?>
                                                    <p class="mb-0"><span class="badge <?php echo $status_class; ?>"><?php echo $status_text; ?></span></p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="mt-4">
                                        <div class="d-flex flex-wrap gap-2">
                                            <a href="edit_role.php?id=<?php echo $role_id; ?>" class="btn btn-primary">
                                                <i class="ri-edit-box-line align-bottom me-1"></i> Edit Role
                                            </a>
                                            <a href="all_roles.php" class="btn btn-light">
                                                <i class="ri-arrow-go-back-line align-bottom me-1"></i> Back to List
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-8">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Menu Permissions</h4>
                                </div>
                                <div class="card-body">
                                    <?php if (count($menu_permissions) > 0): ?>
                                        <div class="table-responsive">
                                            <table class="table table-striped mb-0">
                                                <thead>
                                                    <tr>
                                                        <th>#</th>
                                                        <th>Menu Item</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php foreach ($menu_permissions as $index => $permission): ?>
                                                        <tr>
                                                            <td><?php echo $index + 1; ?></td>
                                                            <td><?php echo htmlspecialchars($permission['menu_item']); ?></td>
                                                        </tr>
                                                    <?php endforeach; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    <?php else: ?>
                                        <div class="alert alert-info">
                                            No menu permissions found for this role.
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Users with this Role</h4>
                                </div>
                                <div class="card-body">
                                    <?php if ($users_result->num_rows > 0): ?>
                                        <div class="table-responsive">
                                            <table id="users-table" class="table table-bordered dt-responsive nowrap">
                                                <thead>
                                                    <tr>
                                                        <th>Username</th>
                                                        <th>Full Name</th>
                                                        <th>Email</th>
                                                        <th>Created Date</th>
                                                        <th>Last Active</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>
                                                            <td><?php echo date('d M Y', strtotime($user['created_at'])); ?></td>
                                                            <td>
                                                                <?php 
                                                                if (!empty($user['last_active'])) {
                                                                    echo date('d M Y H:i', strtotime($user['last_active']));
                                                                } else {
                                                                    echo 'Never';
                                                                }
                                                                ?>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    <?php else: ?>
                                        <div class="alert alert-info">
                                            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'; ?>
    <!-- DataTables -->
    <script src="assets/libs/datatables.net/js/jquery.dataTables.min.js"></script>
    <script src="assets/libs/datatables.net-bs4/js/dataTables.bootstrap4.min.js"></script>
    <script src="assets/libs/datatables.net-responsive/js/dataTables.responsive.min.js"></script>
    <script src="assets/libs/datatables.net-responsive-bs4/js/responsive.bootstrap4.min.js"></script>
    
    <script src="assets/js/app.js"></script>
    
    <script>
        $(document).ready(function() {
            // Initialize DataTable for users
            $('#users-table').DataTable({
                language: {
                    paginate: {
                        previous: "<i class='mdi mdi-chevron-left'>",
                        next: "<i class='mdi mdi-chevron-right'>"
                    }
                },
                drawCallback: function() {
                    $('.dataTables_paginate > .pagination').addClass('pagination-rounded');
                }
            });
        });
    </script>
</body>
</html>