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

// Set timezone
date_default_timezone_set('Africa/Nairobi');

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

$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role_name'] ?? 'User';

// Check if user has permission to manage permissions
if ($user_role !== 'Administrator') {
    header('Location: index.php');
    exit();
}

// Fetch user details
$sql_user = "SELECT u.*, ur.role_name FROM users u 
             INNER JOIN user_roles ur ON u.role_id = ur.role_id 
             WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if (!$user_details) {
    header('Location: logout.php');
    exit();
}

// Handle AJAX requests
if (isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    switch ($_POST['action']) {
        case 'create_permission':
            $name = trim($_POST['name']);
            $description = trim($_POST['description']);
            $category = trim($_POST['category']);
            
            // Validation
            if (empty($name)) {
                echo json_encode(['success' => false, 'message' => 'Permission name is required']);
                exit();
            }
            
            if (empty($category)) {
                echo json_encode(['success' => false, 'message' => 'Category is required']);
                exit();
            }
            
            // Check for duplicate permission name
            $check_sql = "SELECT permission_id FROM permissions WHERE name = ?";
            $stmt_check = $conn->prepare($check_sql);
            $stmt_check->bind_param("s", $name);
            $stmt_check->execute();
            if ($stmt_check->get_result()->num_rows > 0) {
                echo json_encode(['success' => false, 'message' => 'Permission name already exists']);
                exit();
            }
            
            $insert_sql = "INSERT INTO permissions (name, description, category) VALUES (?, ?, ?)";
            $stmt = $conn->prepare($insert_sql);
            $stmt->bind_param("sss", $name, $description, $category);
            
            if ($stmt->execute()) {
                $permission_id = $conn->insert_id;
                
                // Log activity
                $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, new_values) 
                           VALUES (?, 'CREATE', 'permissions', ?, ?)";
                $stmt_log = $conn->prepare($log_sql);
                $log_data = json_encode(['name' => $name, 'category' => $category]);
                $stmt_log->bind_param("iss", $user_id, $permission_id, $log_data);
                $stmt_log->execute();
                
                echo json_encode(['success' => true, 'message' => 'Permission created successfully', 'permission_id' => $permission_id]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to create permission']);
            }
            break;
            
        case 'update_permission':
            $permission_id = intval($_POST['permission_id']);
            $name = trim($_POST['name']);
            $description = trim($_POST['description']);
            $category = trim($_POST['category']);
            
            $update_sql = "UPDATE permissions SET name = ?, description = ?, category = ? WHERE permission_id = ?";
            $stmt = $conn->prepare($update_sql);
            $stmt->bind_param("sssi", $name, $description, $category, $permission_id);
            
            if ($stmt->execute()) {
                // Log activity
                $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, new_values) 
                           VALUES (?, 'UPDATE', 'permissions', ?, ?)";
                $stmt_log = $conn->prepare($log_sql);
                $log_data = json_encode(['name' => $name, 'category' => $category]);
                $stmt_log->bind_param("iss", $user_id, $permission_id, $log_data);
                $stmt_log->execute();
                
                echo json_encode(['success' => true, 'message' => 'Permission updated successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to update permission']);
            }
            break;
            
        case 'delete_permission':
            $permission_id = intval($_POST['permission_id']);
            
            // Check if permission is assigned to any roles
            $roles_check = $conn->prepare("SELECT COUNT(*) as count FROM role_permissions WHERE permission_id = ?");
            $roles_check->bind_param("i", $permission_id);
            $roles_check->execute();
            $role_count = $roles_check->get_result()->fetch_assoc()['count'];
            
            if ($role_count > 0) {
                echo json_encode(['success' => false, 'message' => "Cannot delete permission. It is assigned to {$role_count} role(s)."]);
                exit();
            }
            
            $delete_sql = "DELETE FROM permissions WHERE permission_id = ?";
            $stmt = $conn->prepare($delete_sql);
            $stmt->bind_param("i", $permission_id);
            
            if ($stmt->execute()) {
                // Log activity
                $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, old_values) 
                           VALUES (?, 'DELETE', 'permissions', ?, 'permission_deleted')";
                $stmt_log = $conn->prepare($log_sql);
                $stmt_log->bind_param("is", $user_id, $permission_id);
                $stmt_log->execute();
                
                echo json_encode(['success' => true, 'message' => 'Permission deleted successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to delete permission']);
            }
            break;
            
        default:
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }
    exit();
}

// Filter parameters
$category_filter = $_GET['category'] ?? '';
$search_term = $_GET['search'] ?? '';

// Build WHERE clause
$where_conditions = [];
$params = [];
$param_types = '';

if ($category_filter) {
    $where_conditions[] = "p.category = ?";
    $params[] = $category_filter;
    $param_types .= 's';
}

if ($search_term) {
    $where_conditions[] = "(p.name LIKE ? OR p.description LIKE ?)";
    $search_param = "%$search_term%";
    $params[] = $search_param;
    $params[] = $search_param;
    $param_types .= 'ss';
}

$where_clause = empty($where_conditions) ? '' : 'WHERE ' . implode(' AND ', $where_conditions);

// Get permissions with role count
$sql_permissions = "
    SELECT 
        p.*,
        COUNT(DISTINCT rp.role_id) as role_count,
        GROUP_CONCAT(DISTINCT ur.role_name SEPARATOR ', ') as assigned_roles
    FROM permissions p
    LEFT JOIN role_permissions rp ON p.permission_id = rp.permission_id
    LEFT JOIN user_roles ur ON rp.role_id = ur.role_id
    $where_clause
    GROUP BY p.permission_id, p.name, p.description, p.category
    ORDER BY p.category, p.name";

$stmt_permissions = $conn->prepare($sql_permissions);
if (!empty($params)) {
    $stmt_permissions->bind_param($param_types, ...$params);
}
$stmt_permissions->execute();
$permissions_result = $stmt_permissions->get_result();

// Group permissions by category
$permissions_by_category = [];
while ($permission = $permissions_result->fetch_assoc()) {
    $category = $permission['category'];
    if (!isset($permissions_by_category[$category])) {
        $permissions_by_category[$category] = [];
    }
    $permissions_by_category[$category][] = $permission;
}

// Get available categories
$sql_categories = "SELECT DISTINCT category FROM permissions ORDER BY category";
$categories_result = $conn->query($sql_categories);

// Get permission statistics
$sql_stats = "
    SELECT 
        COUNT(*) as total_permissions,
        COUNT(DISTINCT category) as total_categories,
        (SELECT COUNT(*) FROM role_permissions) as total_assignments,
        COUNT(CASE WHEN p.permission_id IN (SELECT permission_id FROM role_permissions) THEN 1 END) as assigned_permissions
    FROM permissions p";

$stats_result = $conn->query($sql_stats);
$stats = $stats_result->fetch_assoc();

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Permissions Management')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- DataTables CSS -->
    <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.bootstrap5.min.css" rel="stylesheet">
    
    <!-- SweetAlert2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    
    <!-- Remix Icons -->
    <link href="https://cdn.jsdelivr.net/npm/remixicon@3.5.0/fonts/remixicon.css" rel="stylesheet">
    
    <style>
        .permission-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            border: 1px solid #e3e6f0;
            transition: all 0.3s ease;
            margin-bottom: 1.5rem;
        }
        
        .permission-card:hover {
            box-shadow: 0 4px 15px rgba(0,0,0,0.15);
            transform: translateY(-2px);
        }
        
        .summary-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 1.5rem;
            position: relative;
            overflow: hidden;
        }
        
        .summary-card::before {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            width: 100px;
            height: 100px;
            background: rgba(255,255,255,0.1);
            border-radius: 50%;
            transform: translate(30px, -30px);
        }
        
        .summary-value {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .summary-label {
            font-size: 0.9rem;
            opacity: 0.9;
        }
        
        .category-section {
            margin-bottom: 2rem;
        }
        
        .category-header {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            padding: 1rem 1.5rem;
            border-radius: 10px 10px 0 0;
            border-bottom: 2px solid #dee2e6;
            margin-bottom: 0;
        }
        
        .category-title {
            font-size: 1.25rem;
            font-weight: 600;
            color: #495057;
            margin: 0;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .category-count {
            background: #6f42c1;
            color: white;
            padding: 0.25rem 0.75rem;
            border-radius: 15px;
            font-size: 0.8rem;
        }
        
        .permission-item {
            background: white;
            border: 1px solid #e9ecef;
            border-top: none;
            padding: 1.25rem 1.5rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: all 0.2s ease;
        }
        
        .permission-item:last-child {
            border-radius: 0 0 10px 10px;
        }
        
        .permission-item:hover {
            background: #f8f9fa;
        }
        
        .permission-info {
            flex-grow: 1;
        }
        
        .permission-name {
            font-size: 1rem;
            font-weight: 600;
            color: #495057;
            margin-bottom: 0.25rem;
        }
        
        .permission-description {
            color: #6c757d;
            font-size: 0.9rem;
            margin-bottom: 0.5rem;
        }
        
        .permission-meta {
            display: flex;
            gap: 1rem;
            font-size: 0.8rem;
            color: #6c757d;
        }
        
        .role-assignments {
            color: #17a2b8;
            font-weight: 500;
        }
        
        .action-btn {
            padding: 0.5rem 1rem;
            border-radius: 6px;
            font-size: 0.85rem;
            margin: 0.25rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
            font-weight: 500;
        }
        
        .btn-edit { background: #fff3e0; color: #ef6c00; }
        .btn-delete { background: #ffebee; color: #c62828; }
        
        .action-btn:hover {
            transform: scale(1.05);
        }
        
        .create-permission-btn {
            background: linear-gradient(45deg, #28a745, #20c997);
            border: none;
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 10px;
            font-weight: 600;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(40,167,69,0.3);
        }
        
        .create-permission-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(40,167,69,0.4);
            color: white;
        }
        
        .filter-section {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            border: 1px solid #e9ecef;
        }
        
        .category-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.2rem;
        }
        
        @media (max-width: 768px) {
            .permission-item {
                flex-direction: column;
                align-items: flex-start;
                gap: 1rem;
            }
            
            .permission-meta {
                flex-direction: column;
                gap: 0.5rem;
            }
            
            .category-title {
                font-size: 1.1rem;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Header -->
                    <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"><i class="ri-key-line me-2"></i>Permissions Management</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="manage_roles.php">User Management</a></li>
                                        <li class="breadcrumb-item active">Permissions</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Summary Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                                <div class="summary-value"><?php echo number_format($stats['total_permissions']); ?></div>
                                <div class="summary-label">Total Permissions</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                                <div class="summary-value"><?php echo number_format($stats['total_categories']); ?></div>
                                <div class="summary-label">Categories</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
                                <div class="summary-value"><?php echo number_format($stats['assigned_permissions']); ?></div>
                                <div class="summary-label">Assigned Permissions</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);">
                                <div class="summary-value"><?php echo number_format($stats['total_assignments']); ?></div>
                                <div class="summary-label">Total Assignments</div>
                            </div>
                        </div>
                    </div>

                    <!-- Actions and Filters -->
                    <div class="row">
                        <div class="col-12">
                            <div class="permission-card">
                                <div class="card-body">
                                    <div class="row align-items-center">
                                        <div class="col-md-6">
                                            <button class="btn create-permission-btn me-2" onclick="showCreatePermissionModal()">
                                                <i class="ri-add-line me-1"></i>Create Permission
                                            </button>
                                            <a href="manage_roles.php" class="btn btn-outline-primary me-2">
                                                <i class="ri-shield-user-line me-1"></i>Manage Roles
                                            </a>
                                            <button class="btn btn-outline-info" onclick="exportPermissions()">
                                                <i class="ri-download-line me-1"></i>Export
                                            </button>
                                        </div>
                                        <div class="col-md-6 text-end">
                                            <button class="btn btn-outline-primary" type="button" data-bs-toggle="collapse" data-bs-target="#filterSection">
                                                <i class="ri-filter-3-line me-1"></i>Filters
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filter Section -->
                    <div class="collapse" id="filterSection">
                        <div class="filter-section">
                            <form method="GET" class="row g-3">
                                <div class="col-md-3">
                                    <label for="category" class="form-label">Category</label>
                                    <select class="form-select" name="category" id="category">
                                        <option value="">All Categories</option>
                                        <?php 
                                        $categories_result->data_seek(0);
                                        while ($category = $categories_result->fetch_assoc()): 
                                        ?>
                                        <option value="<?php echo $category['category']; ?>" <?php echo $category_filter == $category['category'] ? 'selected' : ''; ?>>
                                            <?php echo $category['category']; ?>
                                        </option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>
                                
                                <div class="col-md-6">
                                    <label for="search" class="form-label">Search</label>
                                    <input type="text" class="form-control" name="search" id="search" 
                                           placeholder="Search permissions..." value="<?php echo htmlspecialchars($search_term); ?>">
                                </div>
                                
                                <div class="col-md-3">
                                    <label class="form-label">&nbsp;</label>
                                    <div class="d-flex gap-2">
                                        <button type="submit" class="btn btn-primary flex-fill">
                                            <i class="ri-search-line me-1"></i>Search
                                        </button>
                                        <a href="permissions.php" class="btn btn-outline-secondary">
                                            <i class="ri-refresh-line"></i>
                                        </a>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Permissions by Category -->
                    <div class="row">
                        <div class="col-12">
                            <?php if (empty($permissions_by_category)): ?>
                            <div class="permission-card">
                                <div class="card-body text-center py-5">
                                    <i class="ri-key-line fs-1 text-muted mb-3"></i>
                                    <h5 class="text-muted">No permissions found</h5>
                                    <p class="text-muted"><?php echo $search_term ? 'Try adjusting your search criteria.' : 'Create your first permission to get started.'; ?></p>
                                    <?php if (!$search_term): ?>
                                    <button class="btn create-permission-btn mt-3" onclick="showCreatePermissionModal()">
                                        <i class="ri-add-line me-1"></i>Create First Permission
                                    </button>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <?php else: ?>
                            <?php foreach ($permissions_by_category as $category => $permissions): ?>
                            <div class="category-section">
                                <div class="category-header">
                                    <div class="category-title">
                                        <div class="category-icon">
                                            <i class="ri-key-2-line"></i>
                                        </div>
                                        <?php echo htmlspecialchars($category); ?>
                                        <span class="category-count"><?php echo count($permissions); ?></span>
                                    </div>
                                </div>
                                
                                <?php foreach ($permissions as $permission): ?>
                                <div class="permission-item">
                                    <div class="permission-info">
                                        <div class="permission-name"><?php echo htmlspecialchars($permission['name']); ?></div>
                                        <?php if ($permission['description']): ?>
                                        <div class="permission-description"><?php echo htmlspecialchars($permission['description']); ?></div>
                                        <?php endif; ?>
                                        <div class="permission-meta">
                                            <span class="role-assignments">
                                                <i class="ri-shield-user-line me-1"></i>
                                                <?php echo $permission['role_count']; ?> role(s)
                                            </span>
                                            <?php if ($permission['assigned_roles']): ?>
                                            <span title="<?php echo htmlspecialchars($permission['assigned_roles']); ?>">
                                                <i class="ri-group-line me-1"></i>
                                                <?php echo substr($permission['assigned_roles'], 0, 50) . (strlen($permission['assigned_roles']) > 50 ? '...' : ''); ?>
                                            </span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    
                                    <div class="d-flex">
                                        <button class="action-btn btn-edit" 
                                                onclick="editPermission(<?php echo $permission['permission_id']; ?>, '<?php echo htmlspecialchars($permission['name']); ?>', '<?php echo htmlspecialchars($permission['description']); ?>', '<?php echo htmlspecialchars($permission['category']); ?>')">
                                            <i class="ri-edit-line me-1"></i>Edit
                                        </button>
                                        
                                        <?php if ($permission['role_count'] == 0): ?>
                                        <button class="action-btn btn-delete" 
                                                onclick="deletePermission(<?php echo $permission['permission_id']; ?>, '<?php echo htmlspecialchars($permission['name']); ?>')">
                                            <i class="ri-delete-bin-line me-1"></i>Delete
                                        </button>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Create/Edit Permission Modal -->
    <div class="modal fade" id="permissionModal" tabindex="-1" aria-labelledby="permissionModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="permissionModalLabel">
                        <i class="ri-key-line me-2"></i>Create Permission
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="permissionForm">
                    <div class="modal-body">
                        <input type="hidden" id="permission_id" name="permission_id">
                        <input type="hidden" id="form_action" name="action" value="create_permission">
                        
                        <div class="mb-3">
                            <label for="permission_name" class="form-label">Permission Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="permission_name" name="name" required
                                   placeholder="Enter permission name (e.g., users.create, reports.view)">
                            <div class="form-text">Use dot notation for better organization (module.action)</div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="permission_description" class="form-label">Description</label>
                            <textarea class="form-control" id="permission_description" name="description" rows="3"
                                     placeholder="Enter permission description..."></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <label for="permission_category" class="form-label">Category <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <input type="text" class="form-control" id="permission_category" name="category" 
                                       list="categoryList" required placeholder="Enter or select category">
                                <datalist id="categoryList">
                                    <?php 
                                    $categories_result->data_seek(0);
                                    while ($category = $categories_result->fetch_assoc()): 
                                    ?>
                                    <option value="<?php echo htmlspecialchars($category['category']); ?>">
                                    <?php endwhile; ?>
                                    <option value="Users">
                                    <option value="Roles">
                                    <option value="Permissions">
                                    <option value="Customers">
                                    <option value="Shipments">
                                    <option value="Finance">
                                    <option value="Reports">
                                    <option value="Settings">
                                    <option value="System">
                                </datalist>
                            </div>
                        </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-success" id="permissionSubmitBtn">
                            <i class="ri-save-line me-1"></i>Save Permission
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <!-- SweetAlert2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js"></script>
    
    <script>
$(document).ready(function() {
    // Permission form submission
    $('#permissionForm').on('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        
        $.ajax({
            url: 'permissions.php',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    Swal.fire({
                        title: 'Success!',
                        text: response.message,
                        icon: 'success'
                    }).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'
                });
            }
        });
    });
});

// Show create permission modal
function showCreatePermissionModal() {
    $('#permissionModalLabel').html('<i class="ri-key-line me-2"></i>Create Permission');
    $('#form_action').val('create_permission');
    $('#permission_id').val('');
    $('#permission_name').val('');
    $('#permission_description').val('');
    $('#permission_category').val('');
    $('#permissionSubmitBtn').html('<i class="ri-save-line me-1"></i>Create Permission');
    $('#permissionModal').modal('show');
}

// Edit permission
function editPermission(permissionId, name, description, category) {
    $('#permissionModalLabel').html('<i class="ri-edit-line me-2"></i>Edit Permission');
    $('#form_action').val('update_permission');
    $('#permission_id').val(permissionId);
    $('#permission_name').val(name);
    $('#permission_description').val(description);
    $('#permission_category').val(category);
    $('#permissionSubmitBtn').html('<i class="ri-save-line me-1"></i>Update Permission');
    $('#permissionModal').modal('show');
}

// Delete permission
function deletePermission(permissionId, name) {
    Swal.fire({
        title: 'Delete Permission',
        text: `Are you sure you want to delete the permission "${name}"? This action cannot be undone.`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, Delete',
        cancelButtonText: 'Cancel',
        confirmButtonColor: '#d33'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: 'permissions.php',
                method: 'POST',
                data: {
                    action: 'delete_permission',
                    permission_id: permissionId
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        Swal.fire({
                            title: 'Deleted!',
                            text: response.message,
                            icon: 'success'
                        }).then(() => {
                            location.reload();
                        });
                    } else {
                        Swal.fire({
                            title: 'Error',
                            text: response.message,
                            icon: 'error'
                        });
                    }
                },
                error: function() {
                    Swal.fire({
                        title: 'Error',
                        text: 'An error occurred while deleting the permission.',
                        icon: 'error'
                    });
                }
            });
        }
    });
}

// Export permissions
function exportPermissions() {
    Swal.fire({
        title: 'Export Permissions',
        html: `
            <div class="mb-3">
                <label class="form-label">Export Format:</label>
                <select class="form-select" id="exportFormat">
                    <option value="excel">Excel (.xlsx)</option>
                    <option value="pdf">PDF Report</option>
                    <option value="csv">CSV Data</option>
                </select>
            </div>
            <div class="mb-3">
                <label class="form-label">Include:</label>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="includeRoleAssignments" checked>
                    <label class="form-check-label" for="includeRoleAssignments">Role Assignments</label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="groupByCategory" checked>
                    <label class="form-check-label" for="groupByCategory">Group by Category</label>
                </div>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Export',
        preConfirm: () => {
            return {
                format: document.getElementById('exportFormat').value,
                includeRoleAssignments: document.getElementById('includeRoleAssignments').checked,
                groupByCategory: document.getElementById('groupByCategory').checked
            };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            const { format } = result.value;
            
            Swal.fire({
                title: 'Generating Export...',
                text: 'Please wait while we prepare your export.',
                icon: 'info',
                allowOutsideClick: false,
                showConfirmButton: false,
                didOpen: () => {
                    Swal.showLoading();
                    setTimeout(() => {
                        Swal.close();
                        // Trigger download
                        const link = document.createElement('a');
                        link.href = `exports/permissions_export.php?format=${format}`;
                        link.download = `permissions_${new Date().toISOString().split('T')[0]}.${format}`;
                        link.click();
                    }, 2000);
                }
            });
        }
    });
}
    </script>

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