<?php include 'services/session.php'; 

// Check if user is logged in
if (!$_SESSION['user'] || !isset($_SESSION['user'])) {
    header('Location: auth-login.php?error=session_expired');
    exit();
}

// Get user role and permissions
$user_role = $_SESSION['role_name'] ?? 'Customer';
$user_id = $_SESSION['user_id'] ?? 0;

// Check if user has permission to manage roles
if (!in_array($user_role, ['Administrator'])) {
    $_SESSION['error'] = "You don't have permission to access this page.";
    header('Location: dashboard.php');
    exit();
}

// Include database connection
require_once 'layouts/dbconn.php';

// Test database connection
if (!isset($conn) || $conn->connect_error) {
    die("Database connection failed: " . ($conn->connect_error ?? 'Connection variable not set'));
}

// Handle AJAX requests
if (isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    switch ($_POST['action']) {
        case 'toggle_role_status':
            $role_id = (int)$_POST['role_id'];
            
            // Check if role is system role (cannot be disabled)
            $stmt = $conn->prepare("SELECT is_system FROM user_roles WHERE role_id = ?");
            $stmt->bind_param("i", $role_id);
            $stmt->execute();
            $result = $stmt->get_result()->fetch_assoc();
            $stmt->close();
            
            if ($result && $result['is_system']) {
                echo json_encode(['success' => false, 'message' => 'System roles cannot be disabled']);
                exit();
            }
            
            // Toggle role status (we'll add an active field to the table later)
            echo json_encode(['success' => true, 'message' => 'Role status updated successfully']);
            exit();
            
        case 'delete_role':
            $role_id = (int)$_POST['role_id'];
            
            // Check if role is system role
            $stmt = $conn->prepare("SELECT is_system FROM user_roles WHERE role_id = ?");
            $stmt->bind_param("i", $role_id);
            $stmt->execute();
            $result = $stmt->get_result()->fetch_assoc();
            $stmt->close();
            
            if ($result && $result['is_system']) {
                echo json_encode(['success' => false, 'message' => 'System roles cannot be deleted']);
                exit();
            }
            
            // Check if role is in use
            $stmt = $conn->prepare("SELECT COUNT(*) as count FROM users WHERE role_id = ?");
            $stmt->bind_param("i", $role_id);
            $stmt->execute();
            $result = $stmt->get_result()->fetch_assoc();
            $stmt->close();
            
            if ($result['count'] > 0) {
                echo json_encode(['success' => false, 'message' => 'Cannot delete role that is assigned to users']);
                exit();
            }
            
            // Delete role permissions first
            $stmt = $conn->prepare("DELETE FROM role_permissions WHERE role_id = ?");
            $stmt->bind_param("i", $role_id);
            $stmt->execute();
            $stmt->close();
            
            // Delete role
            $stmt = $conn->prepare("DELETE FROM user_roles WHERE role_id = ?");
            $stmt->bind_param("i", $role_id);
            if ($stmt->execute()) {
                echo json_encode(['success' => true, 'message' => 'Role deleted successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to delete role']);
            }
            $stmt->close();
            exit();
    }
}

// Get all roles with user counts and permission counts
$roles_query = "
    SELECT 
        ur.role_id,
        ur.role_name,
        ur.description,
        ur.is_system,
        ur.created_at,
        COUNT(DISTINCT u.user_id) as user_count,
        COUNT(DISTINCT rp.permission_id) as permission_count
    FROM user_roles ur
    LEFT JOIN users u ON ur.role_id = u.role_id
    LEFT JOIN role_permissions rp ON ur.role_id = rp.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
";

$roles_result = $conn->query($roles_query);

// Get permission categories for overview
$permissions_query = "
    SELECT 
        category,
        COUNT(*) as permission_count
    FROM permissions 
    GROUP BY category
    ORDER BY category
";
$permissions_result = $conn->query($permissions_query);

// Get total counts
$total_roles = $roles_result ? $roles_result->num_rows : 0;
$total_permissions_result = $conn->query("SELECT COUNT(*) as total FROM permissions");
$total_permissions = $total_permissions_result ? $total_permissions_result->fetch_assoc()['total'] : 0;

?>
<!DOCTYPE html>
<html lang="en">

<head>
    <?php $title = "Roles & Permissions";
    include 'partials/title-meta.php'; ?>

    <!-- SweetAlert2 -->
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">

    <?php include 'partials/head-css.php'; ?>
</head>

<?php include 'partials/body.php'; ?>

<!-- Begin page -->
<div id="wrapper">

    <?php $pagetitle = "Roles & Permissions";
    include 'partials/menu.php'; ?>

    <!-- ============================================================== -->
    <!-- Start Page Content here -->
    <!-- ============================================================== -->

    <div class="content-page">
        <div class="content">

            <!-- Start Content-->
            <div class="container-fluid">
                
                <!-- start page title -->
                <div class="row">
                    <div class="col-12">
                        <div class="page-title-box">
                            <div class="page-title-right">
                                <ol class="breadcrumb m-0">
                                    <li class="breadcrumb-item"><a href="admin-dashboard.php">Dashboard</a></li>
                                    <li class="breadcrumb-item"><a href="#">Users & Customers</a></li>
                                    <li class="breadcrumb-item active">Roles & Permissions</li>
                                </ol>
                            </div>
                            <h4 class="page-title">Roles & Permissions</h4>
                        </div>
                    </div>
                </div>
                <!-- end page title -->

                <!-- Summary Stats -->
                <div class="row">
                    <div class="col-md-3">
                        <div class="card widget-flat">
                            <div class="card-body">
                                <div class="float-end">
                                    <i class="mdi mdi-shield-account widget-icon"></i>
                                </div>
                                <h5 class="text-muted fw-normal mt-0" title="Total Roles">Total Roles</h5>
                                <h3 class="mt-3 mb-3"><?php echo number_format($total_roles); ?></h3>
                                <p class="mb-0 text-muted">
                                    <span class="text-nowrap">User access levels</span>
                                </p>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-3">
                        <div class="card widget-flat">
                            <div class="card-body">
                                <div class="float-end">
                                    <i class="mdi mdi-key widget-icon bg-success-lighten text-success"></i>
                                </div>
                                <h5 class="text-muted fw-normal mt-0" title="Total Permissions">Permissions</h5>
                                <h3 class="mt-3 mb-3"><?php echo number_format($total_permissions); ?></h3>
                                <p class="mb-0 text-muted">
                                    <span class="text-nowrap">Available permissions</span>
                                </p>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-3">
                        <div class="card widget-flat">
                            <div class="card-body">
                                <div class="float-end">
                                    <i class="mdi mdi-shield-lock widget-icon bg-warning-lighten text-warning"></i>
                                </div>
                                <h5 class="text-muted fw-normal mt-0" title="System Roles">System Roles</h5>
                                <h3 class="mt-3 mb-3">
                                    <?php 
                                    $system_roles = 0;
                                    if ($roles_result) {
                                        $roles_result->data_seek(0);
                                        while ($role = $roles_result->fetch_assoc()) {
                                            if ($role['is_system']) $system_roles++;
                                        }
                                        $roles_result->data_seek(0);
                                    }
                                    echo $system_roles;
                                    ?>
                                </h3>
                                <p class="mb-0 text-muted">
                                    <span class="text-nowrap">Protected roles</span>
                                </p>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-3">
                        <div class="card widget-flat">
                            <div class="card-body">
                                <div class="float-end">
                                    <i class="mdi mdi-plus widget-icon bg-info-lighten text-info"></i>
                                </div>
                                <h5 class="text-muted fw-normal mt-0" title="Actions">Actions</h5>
                                <div class="mt-3">
                                    <a href="add-role.php" class="btn btn-primary btn-sm">
                                        <i class="mdi mdi-plus me-1"></i>Add Role
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Permission Categories Overview -->
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-body">
                                <h5 class="card-title">Permission Categories</h5>
                                <div class="row">
                                    <?php if ($permissions_result && $permissions_result->num_rows > 0): ?>
                                        <?php while ($category = $permissions_result->fetch_assoc()): ?>
                                            <div class="col-md-2 col-sm-4">
                                                <div class="text-center p-2">
                                                    <div class="avatar-sm bg-light rounded-circle mx-auto mb-2">
                                                        <span class="avatar-title bg-transparent text-primary">
                                                            <i class="mdi mdi-key-variant"></i>
                                                        </span>
                                                    </div>
                                                    <h6 class="mb-1"><?php echo htmlspecialchars($category['category']); ?></h6>
                                                    <p class="text-muted mb-0 small"><?php echo $category['permission_count']; ?> permissions</p>
                                                </div>
                                            </div>
                                        <?php endwhile; ?>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Roles Table -->
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-center mb-3">
                                    <h5 class="card-title mb-0">User Roles</h5>
                                    <a href="add-role.php" class="btn btn-primary btn-sm">
                                        <i class="mdi mdi-plus me-1"></i>Add New Role
                                    </a>
                                </div>

                                <div class="table-responsive">
                                    <table class="table table-hover table-nowrap">
                                        <thead class="table-light">
                                            <tr>
                                                <th>Role</th>
                                                <th>Description</th>
                                                <th>Type</th>
                                                <th>Users</th>
                                                <th>Permissions</th>
                                                <th>Created</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if ($roles_result && $roles_result->num_rows > 0): ?>
                                                <?php while ($role = $roles_result->fetch_assoc()): ?>
                                                    <tr>
                                                        <td>
                                                            <div class="d-flex align-items-center">
                                                                <div class="avatar-sm bg-primary rounded-circle d-flex align-items-center justify-content-center me-2">
                                                                    <i class="mdi mdi-shield text-white"></i>
                                                                </div>
                                                                <div>
                                                                    <h6 class="mb-1 fw-semibold"><?php echo htmlspecialchars($role['role_name']); ?></h6>
                                                                    <?php if ($role['is_system']): ?>
                                                                        <span class="badge bg-warning-lighten text-warning">System Role</span>
                                                                    <?php endif; ?>
                                                                </div>
                                                            </div>
                                                        </td>
                                                        <td>
                                                            <p class="mb-0"><?php echo htmlspecialchars($role['description'] ?? 'No description'); ?></p>
                                                        </td>
                                                        <td>
                                                            <?php if ($role['is_system']): ?>
                                                                <span class="badge bg-warning">System</span>
                                                            <?php else: ?>
                                                                <span class="badge bg-info">Custom</span>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td>
                                                            <span class="fw-semibold"><?php echo number_format($role['user_count']); ?></span>
                                                            <small class="text-muted">users</small>
                                                        </td>
                                                        <td>
                                                            <span class="fw-semibold"><?php echo number_format($role['permission_count']); ?></span>
                                                            <small class="text-muted">permissions</small>
                                                        </td>
                                                        <td>
                                                            <span class="small"><?php echo date('M j, Y', strtotime($role['created_at'])); ?></span>
                                                        </td>
                                                        <td>
                                                            <div class="btn-group" role="group">
                                                                <button type="button" class="btn btn-sm btn-light dropdown-toggle" 
                                                                        data-bs-toggle="dropdown" aria-expanded="false">
                                                                    <i class="mdi mdi-dots-horizontal"></i>
                                                                </button>
                                                                <ul class="dropdown-menu">
                                                                    <li><a class="dropdown-item" href="role-permissions.php?id=<?php echo $role['role_id']; ?>">
                                                                        <i class="mdi mdi-key me-2"></i>Manage Permissions</a></li>
                                                                    <li><a class="dropdown-item" href="role-users.php?id=<?php echo $role['role_id']; ?>">
                                                                        <i class="mdi mdi-account-group me-2"></i>View Users</a></li>
                                                                    
                                                                    <?php if (!$role['is_system']): ?>
                                                                        <li><hr class="dropdown-divider"></li>
                                                                        <li><a class="dropdown-item" href="edit-role.php?id=<?php echo $role['role_id']; ?>">
                                                                            <i class="mdi mdi-pencil me-2"></i>Edit Role</a></li>
                                                                        <li><a class="dropdown-item text-danger role-action" href="#" 
                                                                               data-action="delete_role" data-id="<?php echo $role['role_id']; ?>">
                                                                            <i class="mdi mdi-delete me-2"></i>Delete Role</a></li>
                                                                    <?php endif; ?>
                                                                </ul>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php endwhile; ?>
                                            <?php else: ?>
                                                <tr>
                                                    <td colspan="7" class="text-center py-5">
                                                        <div class="text-muted">
                                                            <i class="mdi mdi-shield-search display-4"></i>
                                                           <p class="mt-3">No roles found.</p>
                                                           <a href="add-role.php" class="btn btn-primary btn-sm">Create First Role</a>
                                                       </div>
                                                   </td>
                                               </tr>
                                           <?php endif; ?>
                                       </tbody>
                                   </table>
                               </div>
                           </div>
                       </div>
                   </div>
               </div>

           </div> <!-- container -->

       </div> <!-- content -->

       <?php include 'partials/footer.php'; ?>

   </div>

   <!-- ============================================================== -->
   <!-- End Page content -->
   <!-- ============================================================== -->

</div>
<!-- END wrapper -->

<?php include 'partials/right-sidebar.php'; ?>

<?php include 'partials/footer-scripts.php'; ?>

<!-- SweetAlert2 -->
<script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>

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

<script>
   $(document).ready(function() {
       // Handle role actions
       $('.role-action').on('click', function(e) {
           e.preventDefault();
           
           const action = $(this).data('action');
           const roleId = $(this).data('id');
           
           let title = '';
           let text = '';
           let confirmButtonText = '';
           let icon = 'warning';
           
           switch(action) {
               case 'delete_role':
                   title = 'Delete Role?';
                   text = 'This action cannot be undone. The role will be permanently deleted.';
                   confirmButtonText = 'Yes, Delete';
                   icon = 'warning';
                   break;
           }
           
           Swal.fire({
               title: title,
               text: text,
               icon: icon,
               showCancelButton: true,
               confirmButtonColor: '#dc3545',
               cancelButtonColor: '#6c757d',
               confirmButtonText: confirmButtonText,
               cancelButtonText: 'Cancel'
           }).then((result) => {
               if (result.isConfirmed) {
                   performRoleAction(action, roleId);
               }
           });
       });
       
       function performRoleAction(action, roleId) {
           $.ajax({
               url: 'list_roles.php',
               type: 'POST',
               data: {
                   action: action,
                   role_id: roleId
               },
               dataType: 'json',
               success: function(response) {
                   if (response.success) {
                       Swal.fire({
                           title: 'Success!',
                           text: response.message,
                           icon: 'success',
                           timer: 2000,
                           showConfirmButton: false
                       }).then(() => {
                           location.reload();
                       });
                   } else {
                       Swal.fire({
                           title: 'Error!',
                           text: response.message,
                           icon: 'error'
                       });
                   }
               },
               error: function() {
                   Swal.fire({
                       title: 'Error!',
                       text: 'An error occurred while processing the request.',
                       icon: 'error'
                   });
               }
           });
       }
   });
</script>

</body>
</html>