<?php
session_start();
include 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Get current user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT username, role_id, full_name, email FROM users WHERE user_id = $user_id";
$result_user_details = $conn->query($sql_user_details);

if ($result_user_details && $row_user_details = $result_user_details->fetch_assoc()) {
    $username = $row_user_details['username'];
    $user_role = $row_user_details['role_id'];
    $full_name = $row_user_details['full_name'];
    $email = $row_user_details['email'];
}

// Handle form submission for creating new role
$success_message = '';
$error_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'create_role') {
    $role_name = trim($_POST['role_name']);
    $description = trim($_POST['description']);
    
    // Validation
    if (empty($role_name)) {
        $error_message = "Role name is required";
    } else {
        // Check if role already exists
        $check_role = $conn->prepare("SELECT role_id FROM user_roles WHERE role_name = ?");
        $check_role->bind_param("s", $role_name);
        $check_role->execute();
        $result = $check_role->get_result();
        
        if ($result->num_rows > 0) {
            $error_message = "Role name already exists";
        } else {
            // Insert new role
            $insert_role = $conn->prepare("INSERT INTO user_roles (role_name, description, created_at) VALUES (?, ?, NOW())");
            $insert_role->bind_param("ss", $role_name, $description);
            
            if ($insert_role->execute()) {
                $success_message = "Role created successfully!";
            } else {
                $error_message = "Error creating role: " . $conn->error;
            }
        }
    }
}

// Handle role deletion
if (isset($_GET['delete_role']) && is_numeric($_GET['delete_role'])) {
    $role_id = (int)$_GET['delete_role'];
    
    // Check if role is system role
    $check_system = $conn->prepare("SELECT is_system FROM user_roles WHERE role_id = ?");
    $check_system->bind_param("i", $role_id);
    $check_system->execute();
    $system_result = $check_system->get_result();
    
    if ($system_result->num_rows > 0) {
        $system_row = $system_result->fetch_assoc();
        if ($system_row['is_system'] == 1) {
            $error_message = "Cannot delete system roles";
        } else {
            // Check if role is being used
            $check_usage = $conn->prepare("SELECT COUNT(*) as user_count FROM users WHERE role_id = ?");
            $check_usage->bind_param("i", $role_id);
            $check_usage->execute();
            $usage_result = $check_usage->get_result();
            $usage_row = $usage_result->fetch_assoc();
            
            if ($usage_row['user_count'] > 0) {
                $error_message = "Cannot delete role. It is assigned to " . $usage_row['user_count'] . " user(s)";
            } else {
                // Safe to delete
                $delete_role = $conn->prepare("DELETE FROM user_roles WHERE role_id = ?");
                $delete_role->bind_param("i", $role_id);
                
                if ($delete_role->execute()) {
                    $success_message = "Role deleted successfully!";
                } else {
                    $error_message = "Error deleting role: " . $conn->error;
                }
            }
        }
    }
}

// Get all roles with user counts
$sql_roles = "SELECT ur.role_id, ur.role_name, ur.description, ur.is_system, ur.created_at,
              COUNT(u.user_id) as user_count
              FROM user_roles ur
              LEFT JOIN users u ON ur.role_id = u.role_id
              GROUP BY ur.role_id, ur.role_name, ur.description, ur.is_system, ur.created_at
              ORDER BY ur.is_system DESC, ur.role_name ASC";
$result_roles = $conn->query($sql_roles);

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Role Management')); ?>
    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Role Management</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item active">Role Management</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Success/Error Messages -->
                    <?php if (!empty($success_message)): ?>
                        <div class="row">
                            <div class="col-12">
                                <div class="alert alert-success alert-dismissible fade show" role="alert">
                                    <i class="ri-check-double-line align-middle me-2"></i>
                                    <?php echo $success_message; ?>
                                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>

                    <?php if (!empty($error_message)): ?>
                        <div class="row">
                            <div class="col-12">
                                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                    <i class="ri-error-warning-line align-middle me-2"></i>
                                    <?php echo $error_message; ?>
                                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>

                    <div class="row">
                        <!-- Role List -->
                        <div class="col-xl-8">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">User Roles</h4>
                                    <div class="flex-shrink-0">
                                        <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#createRoleModal">
                                            <i class="ri-add-line align-middle me-1"></i>Create New Role
                                        </button>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-hover table-centered align-middle table-nowrap mb-0">
                                            <thead class="text-muted table-light">
                                                <tr>
                                                    <th scope="col">Role Name</th>
                                                    <th scope="col">Description</th>
                                                    <th scope="col">Users</th>
                                                    <th scope="col">Type</th>
                                                    <th scope="col">Created</th>
                                                    <th scope="col">Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result_roles && $result_roles->num_rows > 0): ?>
                                                    <?php while($role = $result_roles->fetch_assoc()): ?>
                                                    <tr>
                                                        <td>
                                                            <div class="d-flex align-items-center">
                                                                <?php if ($role['is_system']): ?>
                                                                    <i class="ri-shield-check-line text-primary me-2"></i>
                                                                <?php else: ?>
                                                                    <i class="ri-user-settings-line text-info me-2"></i>
                                                                <?php endif; ?>
                                                                <strong><?php echo htmlspecialchars($role['role_name']); ?></strong>
                                                            </div>
                                                        </td>
                                                        <td>
                                                            <span class="text-muted">
                                                                <?php echo $role['description'] ? htmlspecialchars($role['description']) : 'No description'; ?>
                                                            </span>
                                                        </td>
                                                        <td>
                                                            <span class="badge bg-info">
                                                                <?php echo $role['user_count']; ?> user(s)
                                                            </span>
                                                        </td>
                                                        <td>
                                                            <?php if ($role['is_system']): ?>
                                                                <span class="badge bg-primary">System</span>
                                                            <?php else: ?>
                                                                <span class="badge bg-secondary">Custom</span>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td><?php echo date('d M Y', strtotime($role['created_at'])); ?></td>
                                                        <td>
                                                            <div class="dropdown">
                                                                <button class="btn btn-soft-secondary btn-sm dropdown-toggle" type="button" data-bs-toggle="dropdown">
                                                                    <i class="ri-more-fill"></i>
                                                                </button>
                                                                <ul class="dropdown-menu dropdown-menu-end">
                                                                    <li>
                                                                        <a class="dropdown-item" href="edit_role.php?id=<?php echo $role['role_id']; ?>">
                                                                            <i class="ri-pencil-fill text-muted me-2"></i>Edit
                                                                        </a>
                                                                    </li>
                                                                    <?php if (!$role['is_system'] && $role['user_count'] == 0): ?>
                                                                    <li>
                                                                        <a class="dropdown-item text-danger" href="?delete_role=<?php echo $role['role_id']; ?>" 
                                                                           onclick="return confirm('Are you sure you want to delete this role?')">
                                                                            <i class="ri-delete-bin-fill me-2"></i>Delete
                                                                        </a>
                                                                    </li>
                                                                    <?php endif; ?>
                                                                </ul>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="6" class="text-center py-4">
                                                            <div class="text-muted">
                                                                <i class="ri-database-2-line fs-24 mb-2 d-block"></i>
                                                                No roles found
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Statistics -->
                        <div class="col-xl-4">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Role Statistics</h4>
                                </div>
                                <div class="card-body">
                                    <?php 
                                    // Calculate statistics
                                    $result_roles->data_seek(0); // Reset pointer
                                    $total_roles = 0;
                                    $system_roles = 0;
                                    $custom_roles = 0;
                                    $total_users = 0;
                                    
                                    while($role = $result_roles->fetch_assoc()) {
                                        $total_roles++;
                                        $total_users += $role['user_count'];
                                        if ($role['is_system']) {
                                            $system_roles++;
                                        } else {
                                            $custom_roles++;
                                        }
                                    }
                                    ?>
                                    
                                    <div class="row text-center">
                                        <div class="col-6">
                                            <div class="p-3 border rounded">
                                                <h4 class="mb-1"><?php echo $total_roles; ?></h4>
                                                <p class="text-muted mb-0">Total Roles</p>
                                            </div>
                                        </div>
                                        <div class="col-6">
                                            <div class="p-3 border rounded">
                                                <h4 class="mb-1"><?php echo $total_users; ?></h4>
                                                <p class="text-muted mb-0">Total Users</p>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="row text-center mt-3">
                                        <div class="col-6">
                                            <div class="p-3 border rounded">
                                                <h4 class="mb-1 text-primary"><?php echo $system_roles; ?></h4>
                                                <p class="text-muted mb-0">System Roles</p>
                                            </div>
                                        </div>
                                        <div class="col-6">
                                            <div class="p-3 border rounded">
                                                <h4 class="mb-1 text-info"><?php echo $custom_roles; ?></h4>
                                                <p class="text-muted mb-0">Custom Roles</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Help -->
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Role Management Help</h4>
                                </div>
                                <div class="card-body">
                                    <div class="alert alert-info">
                                        <h6 class="alert-heading">Guidelines:</h6>
                                        <ul class="mb-0 ps-3">
                                            <li><strong>System Roles:</strong> Cannot be deleted, core to system functionality</li>
                                            <li><strong>Custom Roles:</strong> Can be created, edited, or deleted</li>
                                            <li>Roles with assigned users cannot be deleted</li>
                                            <li>Role names must be unique</li>
                                        </ul>
                                    </div>
                                    
                                    <div class="mt-3">
                                        <h6>Quick Actions:</h6>
                                        <div class="d-grid gap-2">
                                            <a href="users.php" class="btn btn-outline-primary btn-sm">
                                                <i class="ri-group-line me-1"></i>View All Users
                                            </a>
                                            <a href="create_user.php" class="btn btn-outline-success btn-sm">
                                                <i class="ri-user-add-line me-1"></i>Create New User
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Create Role Modal -->
    <div class="modal fade" id="createRoleModal" tabindex="-1" aria-labelledby="createRoleModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="createRoleModalLabel">Create New Role</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="POST" id="createRoleForm">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="create_role">
                        
                        <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" required>
                            <div class="form-text">Enter a unique role name</div>
                        </div>

                        <div class="mb-3">
                            <label for="description" class="form-label">Description</label>
                            <textarea class="form-control" id="description" name="description" rows="3" 
                                      placeholder="Describe the role's responsibilities and permissions"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="ri-save-line me-1"></i>Create Role
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <script>
        // Form validation
        document.getElementById('createRoleForm').addEventListener('submit', function(e) {
            const roleName = document.getElementById('role_name').value.trim();
            
            if (roleName === '') {
                e.preventDefault();
                alert('Role name is required!');
                return false;
            }
        });

        // Auto-hide alerts after 5 seconds
        setTimeout(function() {
            const alerts = document.querySelectorAll('.alert');
            alerts.forEach(function(alert) {
                const bsAlert = new bootstrap.Alert(alert);
                bsAlert.close();
            });
        }, 5000);
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>