<?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'];
}

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

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

// Get role details
$sql_role = "SELECT role_id, role_name, description, is_system, created_at FROM user_roles WHERE role_id = ?";
$stmt_role = $conn->prepare($sql_role);
$stmt_role->bind_param("i", $role_id);
$stmt_role->execute();
$result_role = $stmt_role->get_result();

if ($result_role->num_rows === 0) {
    header('Location: manage_roles.php');
    exit();
}

$role = $result_role->fetch_assoc();

// Get count of users with this role
$sql_user_count = "SELECT COUNT(*) as user_count FROM users WHERE role_id = ?";
$stmt_user_count = $conn->prepare($sql_user_count);
$stmt_user_count->bind_param("i", $role_id);
$stmt_user_count->execute();
$user_count = $stmt_user_count->get_result()->fetch_assoc()['user_count'];

// Get users with this role
$sql_users = "SELECT user_id, username, full_name, email, status, created_at, last_login 
              FROM users WHERE role_id = ? ORDER BY full_name";
$stmt_users = $conn->prepare($sql_users);
$stmt_users->bind_param("i", $role_id);
$stmt_users->execute();
$result_users = $stmt_users->get_result();

// Handle form submission
$success_message = '';
$error_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $new_role_name = trim($_POST['role_name']);
    $new_description = trim($_POST['description']);
    
    // Validation
    if (empty($new_role_name)) {
        $error_message = "Role name is required";
    } else {
        // Check if role name already exists (excluding current role)
        $check_role = $conn->prepare("SELECT role_id FROM user_roles WHERE role_name = ? AND role_id != ?");
        $check_role->bind_param("si", $new_role_name, $role_id);
        $check_role->execute();
        $result = $check_role->get_result();
        
        if ($result->num_rows > 0) {
            $error_message = "Role name already exists";
        } else {
            // Update role
            $update_role = $conn->prepare("UPDATE user_roles SET role_name = ?, description = ? WHERE role_id = ?");
            $update_role->bind_param("ssi", $new_role_name, $new_description, $role_id);
            
            if ($update_role->execute()) {
                $success_message = "Role updated successfully!";
                // Update the role array for display
                $role['role_name'] = $new_role_name;
                $role['description'] = $new_description;
            } else {
                $error_message = "Error updating role: " . $conn->error;
            }
        }
    }
}

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Edit Role')); ?>
    <?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">Edit Role: <?php echo htmlspecialchars($role['role_name']); ?></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"><a href="manage_roles.php">Role Management</a></li>
                                        <li class="breadcrumb-item active">Edit Role</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 Edit Form -->
                        <div class="col-xl-8">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Role Information</h4>
                                </div>
                                <div class="card-body">
                                    <?php if ($role['is_system']): ?>
                                        <div class="alert alert-warning">
                                            <i class="ri-shield-check-line me-2"></i>
                                            <strong>System Role:</strong> This is a system role. Some modifications may be restricted.
                                        </div>
                                    <?php endif; ?>

                                    <form method="POST" id="editRoleForm">
                                        <div class="row">
                                            <div class="col-md-12">
                                                <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']); ?>" 
                                                           <?php echo $role['is_system'] ? 'readonly' : 'required'; ?>>
                                                    <div class="form-text">Role name must be unique</div>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-12">
                                                <div class="mb-3">
                                                    <label for="description" class="form-label">Description</label>
                                                    <textarea class="form-control" id="description" name="description" rows="4" 
                                                              placeholder="Describe the role's responsibilities and permissions"><?php echo htmlspecialchars($role['description'] ?? ''); ?></textarea>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="mt-4">
                                            <button type="submit" class="btn btn-primary" <?php echo $role['is_system'] ? 'disabled' : ''; ?>>
                                                <i class="ri-save-line align-middle me-2"></i>Update Role
                                            </button>
                                            <a href="manage_roles.php" class="btn btn-secondary ms-2">
                                                <i class="ri-arrow-left-line align-middle me-2"></i>Back to Roles
                                            </a>
                                        </div>
                                    </form>
                                </div>
                            </div>

                            <!-- Users with this Role -->
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Users with this Role (<?php echo $user_count; ?>)</h4>
                                </div>
                                <div class="card-body">
                                    <?php if ($result_users && $result_users->num_rows > 0): ?>
                                        <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">User</th>
                                                        <th scope="col">Email</th>
                                                        <th scope="col">Status</th>
                                                        <th scope="col">Last Login</th>
                                                        <th scope="col">Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php while($user = $result_users->fetch_assoc()): ?>
                                                    <tr>
                                                        <td>
                                                            <div class="d-flex align-items-center">
                                                                <div class="avatar-sm flex-shrink-0 me-3">
                                                                    <div class="avatar-title bg-primary-subtle text-primary rounded-circle">
                                                                        <?php echo strtoupper(substr($user['full_name'], 0, 1)); ?>
                                                                    </div>
                                                                </div>
                                                                <div>
                                                                    <h6 class="mb-1"><?php echo htmlspecialchars($user['full_name']); ?></h6>
                                                                    <p class="text-muted mb-0">@<?php echo htmlspecialchars($user['username']); ?></p>
                                                                </div>
                                                            </div>
                                                        </td>
                                                        <td><?php echo htmlspecialchars($user['email']); ?></td>
                                                        <td>
                                                            <?php
                                                            $status_class = '';
                                                            switch($user['status']) {
                                                                case 'ACTIVE':
                                                                    $status_class = 'bg-success';
                                                                    break;
                                                                case 'INACTIVE':
                                                                    $status_class = 'bg-secondary';
                                                                    break;
                                                                case 'SUSPENDED':
                                                                    $status_class = 'bg-danger';
                                                                    break;
                                                            }
                                                            ?>
                                                            <span class="badge <?php echo $status_class; ?>">
                                                                <?php echo ucfirst(strtolower($user['status'])); ?>
                                                            </span>
                                                        </td>
                                                        <td>
                                                            <?php if ($user['last_login']): ?>
                                                                <?php echo date('d M Y H:i', strtotime($user['last_login'])); ?>
                                                            <?php else: ?>
                                                                <span class="text-muted">Never</span>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td>
                                                            <a href="edit_user.php?id=<?php echo $user['user_id']; ?>" class="btn btn-soft-primary btn-sm">
                                                                <i class="ri-pencil-fill"></i>
                                                            </a>
                                                        </td>
                                                    </tr>
                                                    <?php endwhile; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    <?php else: ?>
                                        <div class="text-center py-4">
                                            <div class="text-muted">
                                                <i class="ri-user-line fs-24 mb-2 d-block"></i>
                                                No users assigned to this role
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>

                        <!-- Role Information Sidebar -->
                        <div class="col-xl-4">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Role Details</h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-borderless mb-0">
                                            <tbody>
                                                <tr>
                                                    <td class="fw-medium">Role ID:</td>
                                                    <td><?php echo $role['role_id']; ?></td>
                                                </tr>
                                                <tr>
                                                    <td class="fw-medium">Role Type:</td>
                                                    <td>
                                                        <?php if ($role['is_system']): ?>
                                                            <span class="badge bg-primary">System Role</span>
                                                        <?php else: ?>
                                                            <span class="badge bg-secondary">Custom Role</span>
                                                        <?php endif; ?>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td class="fw-medium">Users Assigned:</td>
                                                    <td>
                                                        <span class="badge bg-info"><?php echo $user_count; ?> user(s)</span>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td class="fw-medium">Created:</td>
                                                    <td><?php echo date('d M Y', strtotime($role['created_at'])); ?></td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>

                            <!-- Role Actions -->
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Quick Actions</h4>
                                </div>
                                <div class="card-body">
                                    <div class="d-grid gap-2">
                                        <a href="users.php?role=<?php echo $role_id; ?>" class="btn btn-outline-primary btn-sm">
                                            <i class="ri-group-line me-1"></i>View All Users with this Role
                                        </a>
                                        <a href="create_user.php?role=<?php echo $role_id; ?>" class="btn btn-outline-success btn-sm">
                                            <i class="ri-user-add-line me-1"></i>Create User with this Role
                                        </a>
                                        <?php if (!$role['is_system'] && $user_count == 0): ?>
                                        <a href="manage_roles.php?delete_role=<?php echo $role_id; ?>" 
                                           class="btn btn-outline-danger btn-sm"
                                           onclick="return confirm('Are you sure you want to delete this role? This action cannot be undone.')">
                                            <i class="ri-delete-bin-line me-1"></i>Delete Role
                                        </a>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>

                            <!-- Help Section -->
                            <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>System roles cannot be renamed or deleted</li>
                                            <li>Only custom roles can be fully modified</li>
                                            <li>Roles with assigned users cannot be deleted</li>
                                            <li>Consider impact on users before making changes</li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <script>
        // Form validation
        document.getElementById('editRoleForm').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>