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

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

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

// Get user details and role verification
$user_id = $_SESSION['user_id'];
$sql_user_details = "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_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if (!$user_details || $user_details['role_name'] !== 'Super Admin') {
    header('Location: dashboard.php');
    exit();
}

$full_name = $user_details['full_name'];
$role_name = $user_details['role_name'];

// Handle form submissions
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add_role':
                $role_name_new = trim($_POST['role_name']);
                $description = trim($_POST['description']);
                
                // Check if role name already exists
                $sql_check = "SELECT role_id FROM user_roles WHERE role_name = ?";
                $stmt_check = $conn->prepare($sql_check);
                $stmt_check->bind_param("s", $role_name_new);
                $stmt_check->execute();
                
                if ($stmt_check->get_result()->num_rows > 0) {
                    $message = "Role name already exists!";
                    $message_type = "error";
                } else {
                    $sql_add = "INSERT INTO user_roles (role_name, description) VALUES (?, ?)";
                    $stmt_add = $conn->prepare($sql_add);
                    $stmt_add->bind_param("ss", $role_name_new, $description);
                    
                    if ($stmt_add->execute()) {
                        $message = "Role added successfully!";
                        $message_type = "success";
                    } else {
                        $message = "Error adding role: " . $conn->error;
                        $message_type = "error";
                    }
                }
                break;
                
            case 'update_role':
                $role_id = (int)$_POST['role_id'];
                $role_name_edit = trim($_POST['edit_role_name']);
                $description_edit = trim($_POST['edit_description']);
                
                // Prevent editing system roles
                $sql_check_system = "SELECT is_system FROM user_roles WHERE role_id = ?";
                $stmt_check_system = $conn->prepare($sql_check_system);
                $stmt_check_system->bind_param("i", $role_id);
                $stmt_check_system->execute();
                $is_system = $stmt_check_system->get_result()->fetch_assoc()['is_system'];
                
                if ($is_system) {
                    $message = "Cannot edit system roles!";
                    $message_type = "error";
                } else {
                    $sql_update = "UPDATE user_roles SET role_name = ?, description = ? WHERE role_id = ? AND is_system = 0";
                    $stmt_update = $conn->prepare($sql_update);
                    $stmt_update->bind_param("ssi", $role_name_edit, $description_edit, $role_id);
                    
                    if ($stmt_update->execute()) {
                        $message = "Role updated successfully!";
                        $message_type = "success";
                    } else {
                        $message = "Error updating role: " . $conn->error;
                        $message_type = "error";
                    }
                }
                break;
                
            case 'add_page_permission':
                $role_id = (int)$_POST['permission_role_id'];
                $page_name = trim($_POST['page_name']);
                
                // Check if permission already exists
                $sql_check_perm = "SELECT id FROM role_page_permissions WHERE role_id = ? AND page_name = ?";
                $stmt_check_perm = $conn->prepare($sql_check_perm);
                $stmt_check_perm->bind_param("is", $role_id, $page_name);
                $stmt_check_perm->execute();
                
                if ($stmt_check_perm->get_result()->num_rows > 0) {
                    $message = "Permission already exists for this role!";
                    $message_type = "error";
                } else {
                    $sql_add_perm = "INSERT INTO role_page_permissions (role_id, page_name) VALUES (?, ?)";
                    $stmt_add_perm = $conn->prepare($sql_add_perm);
                    $stmt_add_perm->bind_param("is", $role_id, $page_name);
                    
                    if ($stmt_add_perm->execute()) {
                        $message = "Page permission added successfully!";
                        $message_type = "success";
                    } else {
                        $message = "Error adding permission: " . $conn->error;
                        $message_type = "error";
                    }
                }
                break;
                
            case 'remove_permission':
                $permission_id = (int)$_POST['permission_id'];
                
                $sql_remove = "DELETE FROM role_page_permissions WHERE id = ?";
                $stmt_remove = $conn->prepare($sql_remove);
                $stmt_remove->bind_param("i", $permission_id);
                
                if ($stmt_remove->execute()) {
                    $message = "Permission removed successfully!";
                    $message_type = "success";
                } else {
                    $message = "Error removing permission: " . $conn->error;
                    $message_type = "error";
                }
                break;
        }
    }
}

// Get all roles with user counts and permissions
$sql_roles = "SELECT 
    ur.*,
    COUNT(DISTINCT u.user_id) as user_count,
    COUNT(DISTINCT rpp.page_name) as permission_count,
    GROUP_CONCAT(DISTINCT u.full_name ORDER BY u.full_name SEPARATOR ', ') as user_names
FROM user_roles ur
LEFT JOIN users u ON ur.role_id = u.role_id AND u.status = 'ACTIVE'
LEFT JOIN role_page_permissions rpp ON ur.role_id = rpp.role_id
GROUP BY ur.role_id, ur.role_name, ur.description, ur.created_at, ur.is_system
ORDER BY ur.is_system DESC, ur.role_name";
$result_roles = $conn->query($sql_roles);

// Get all page permissions for roles
$sql_permissions = "SELECT 
    rpp.*,
    ur.role_name,
    ur.is_system
FROM role_page_permissions rpp
INNER JOIN user_roles ur ON rpp.role_id = ur.role_id
ORDER BY ur.role_name, rpp.page_name";
$result_permissions = $conn->query($sql_permissions);

// Available pages for permission assignment
$available_pages = [
    // Customer Management
    'register_customer.php' => 'Register Customer',
    'customer_search.php' => 'Customer Search', 
    'list_customers.php' => 'Customer List',
    
    // Order Management
    'new_order.php' => 'New Order',
    'order_status.php' => 'Order Status',
    'ready_orders.php' => 'Ready Orders',
    'pending_orders.php' => 'Pending Orders',
    'inprogress_orders.php' => 'In Progress Orders',
    'all_orders.php' => 'All Orders',
    'update_order_status.php' => 'Update Order Status',
    'order_analytics.php' => 'Order Analytics',
    
    // Payment & Billing
    'process_payment.php' => 'Process Payment',
    'generate_receipt.php' => 'Generate Receipt',
    'daily_sales.php' => 'Daily Sales',
    'list_payments.php' => 'All Payments',
    'payment_methods.php' => 'Payment Methods',
    'outstanding_bills.php' => 'Outstanding Bills',
    
    // Staff Management
    'list_staff.php' => 'Staff List',
    'add_staff.php' => 'Add Staff',
    'staff_performance.php' => 'Staff Performance',
    
    // Inventory
    'check_supplies.php' => 'Check Supplies',
    'request_supplies.php' => 'Request Supplies',
    'inventory_management.php' => 'Inventory Management',
    'stock_management.php' => 'Stock Management',
    'suppliers.php' => 'Suppliers',
    'purchase_orders.php' => 'Purchase Orders',
    
    // Reports & Analytics
    'daily_reports.php' => 'Daily Reports',
    'monthly_revenue.php' => 'Monthly Revenue',
    'daily_revenue.php' => 'Daily Revenue',
    'profit_analysis.php' => 'Profit Analysis',
    'customer_analytics.php' => 'Customer Analytics',
    
    // Services
    'service_pricing.php' => 'Service Pricing',
    'service_types.php' => 'Service Types',
    
    // User Management
    'list_users.php' => 'All Users',
    'add_user.php' => 'Add User',
    'user_roles.php' => 'User Roles',
    
    // System
    'system_settings.php' => 'System Settings',
    'backup_restore.php' => 'Backup & Restore',
    'activity_logs.php' => 'Activity Logs'
];

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'User Roles - User Management')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <style>
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        /* Header Section */
        .page-header {
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
        }
        
        .header-title h1 {
            font-size: 1.875rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .header-subtitle {
            opacity: 0.9;
            font-size: 1rem;
        }
        
        .header-actions {
            display: flex;
            gap: 1rem;
        }
        
        .btn-primary {
            background: rgba(255, 255, 255, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.3);
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            text-decoration: none;
            font-weight: 600;
            transition: all 0.2s ease;
            cursor: pointer;
        }
        
        .btn-primary:hover {
            background: rgba(255, 255, 255, 0.3);
            color: white;
            transform: translateY(-1px);
        }
        
        /* Alert Messages */
        .alert {
            padding: 1rem 1.5rem;
            border-radius: 8px;
            margin-bottom: 1.5rem;
            border: none;
            font-weight: 500;
        }
        
        .alert-success {
            background: #dcfce7;
            color: #166534;
            border-left: 4px solid #22c55e;
        }
        
        .alert-error {
            background: #fee2e2;
            color: #991b1b;
            border-left: 4px solid #ef4444;
        }
        
        /* Tab Navigation */
        .tabs-container {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            overflow: hidden;
            margin-bottom: 2rem;
        }
        
        .tab-nav {
            display: flex;
            background: #f8fafc;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .tab-button {
            flex: 1;
            padding: 1rem 1.5rem;
            border: none;
            background: transparent;
            color: #64748b;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;
            border-bottom: 3px solid transparent;
        }
        
        .tab-button.active {
            color: #f59e0b;
            background: white;
            border-bottom-color: #f59e0b;
        }
        
        .tab-button:hover {
            background: white;
            color: #374151;
        }
        
        .tab-content {
            padding: 2rem;
        }
        
        .tab-pane {
            display: none;
        }
        
        .tab-pane.active {
            display: block;
        }
        
        /* Roles Grid */
        .roles-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .role-card {
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            padding: 1.5rem;
            transition: all 0.2s ease;
        }
        
        .role-card:hover {
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            transform: translateY(-1px);
        }
        
        .role-card.system-role {
            border-left: 4px solid #3b82f6;
            background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
        }
        
        .role-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 1rem;
        }
        
        .role-name {
            font-size: 1.125rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.25rem;
        }
        
        .role-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.7rem;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .badge-system { background: #dbeafe; color: #1d4ed8; }
        .badge-custom { background: #f0fdf4; color: #166534; }
        
        .role-description {
            color: #64748b;
            font-size: 0.875rem;
            line-height: 1.5;
            margin-bottom: 1rem;
        }
        
        .role-stats {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1rem;
            margin-bottom: 1rem;
        }
        
        .stat-item {
            text-align: center;
            padding: 0.75rem;
            background: #f8fafc;
            border-radius: 8px;
        }
        
        .stat-value {
            font-size: 1.5rem;
            font-weight: 700;
            color: #1e293b;
        }
        
        .stat-label {
            font-size: 0.75rem;
            color: #64748b;
            text-transform: uppercase;
        }
        
        .role-users {
            font-size: 0.875rem;
            color: #64748b;
            margin-bottom: 1rem;
        }
        
        .role-actions {
            display: flex;
            gap: 0.5rem;
        }
        
        .btn-sm {
            padding: 0.5rem 1rem;
            font-size: 0.75rem;
            border-radius: 6px;
            font-weight: 600;
            border: 1px solid;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .btn-warning {
            background: #f59e0b;
            border-color: #f59e0b;
            color: white;
        }
        
        .btn-warning:hover {
            background: #d97706;
            border-color: #d97706;
        }
        
        .btn-info {
            background: #0ea5e9;
            border-color: #0ea5e9;
            color: white;
        }
        
        .btn-info:hover {
            background: #0284c7;
            border-color: #0284c7;
        }
        
        /* Form Styles */
        .form-card {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            padding: 2rem;
        }
        
        .form-title {
            font-size: 1.25rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 1.5rem;
        }
        
        .form-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1.5rem;
            margin-bottom: 1.5rem;
        }
        
        .form-group {
            margin-bottom: 1.5rem;
        }
        
        .form-group.full-width {
            grid-column: 1 / -1;
        }
        
        .form-label {
            font-size: 0.875rem;
            font-weight: 600;
            color: #374151;
            margin-bottom: 0.5rem;
            display: block;
        }
        
        .form-label.required::after {
            content: ' *';
            color: #ef4444;
        }
        
        .form-control {
            width: 100%;
            border: 1px solid #d1d5db;
            border-radius: 8px;
            padding: 0.75rem;
            font-size: 0.875rem;
            transition: border-color 0.2s ease;
        }
        
        .form-control:focus {
            border-color: #f59e0b;
            box-shadow: 0 0 0 3px rgba(245, 158, 11, 0.1);
            outline: none;
        }
        
        .btn-success {
            background: #10b981;
            border: 1px solid #10b981;
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .btn-success:hover {
            background: #059669;
            border-color: #059669;
        }
        
        /* Permissions Table */
        .permissions-table {
            background: white;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
        }
        
        .table-header {
            padding: 1.5rem;
            background: #f8fafc;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .table-title {
            font-size: 1.125rem;
            font-weight: 700;
            color: #1e293b;
            margin: 0;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .data-table th {
            background: #f8fafc;
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            font-size: 0.875rem;
            color: #374151;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .data-table td {
            padding: 1rem;
            border-bottom: 1px solid #f1f5f9;
            font-size: 0.875rem;
        }
        
        .data-table tbody tr:hover {
            background: #f8fafc;
        }
        
        .btn-danger {
            background: #ef4444;
            border: 1px solid #ef4444;
            color: white;
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .btn-danger:hover {
            background: #dc2626;
            border-color: #dc2626;
        }
        
        /* Modal Styles */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            display: none;
            align-items: center;
            justify-content: center;
            z-index: 1000;
        }
        
        .modal-content {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            max-width: 500px;
            width: 90%;
            max-height: 90vh;
            overflow-y: auto;
        }
        
        .modal-header {
            margin-bottom: 1.5rem;
        }
        
        .modal-title {
            font-size: 1.25rem;
            font-weight: 700;
            color: #1e293b;
            margin: 0;
        }
        
        .modal-actions {
            display: flex;
            gap: 1rem;
            justify-content: flex-end;
            margin-top: 2rem;
        }
        
        .btn-cancel {
            background: #64748b;
            border: 1px solid #64748b;
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .btn-cancel:hover {
            background: #475569;
            border-color: #475569;
        }
        
        /* Responsive Design */
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .header-content {
                flex-direction: column;
                text-align: center;
            }
            
            .roles-grid {
                grid-template-columns: 1fr;
            }
            
            .form-grid {
                grid-template-columns: 1fr;
            }
            
            .tab-nav {
                flex-direction: column;
            }
            
            .modal-content {
                width: 95%;
                padding: 1.5rem;
            }
        }
    </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="page-header">
                        <div class="header-content">
                            <div class="header-title">
                                <h1>User Roles Management</h1>
                                <div class="header-subtitle">Manage user roles and page permissions</div>
                            </div>
                            <div class="header-actions">
                                <button onclick="openAddRoleModal()" class="btn-primary">
                                    <i class="ph-plus"></i> Add Role
                                </button>
                                <a href="list_users.php" class="btn-primary">
                                    <i class="ph-users"></i> View Users
                                </a>
                            </div>
                        </div>
                    </div>

                    <!-- Alert Messages -->
                    <?php if (!empty($message)): ?>
                    <div class="alert alert-<?php echo $message_type; ?>">
                        <?php echo $message; ?>
                    </div>
                    <?php endif; ?>

                    <!-- Tabs Container -->
                    <div class="tabs-container">
                        <div class="tab-nav">
                            <button class="tab-button active" onclick="switchTab('roles')">
                                <i class="ph-users"></i> User Roles
                            </button>
                            <button class="tab-button" onclick="switchTab('permissions')">
                                <i class="ph-lock"></i> Page Permissions
                            </button>
                            <button class="tab-button" onclick="switchTab('add-permission')">
                                <i class="ph-plus"></i> Add Permission
                            </button>
                        </div>
                        
                        <div class="tab-content">
                            <!-- Roles Tab -->
                            <div id="roles-tab" class="tab-pane active">
                                <div class="roles-grid">
                                    <?php while($role = $result_roles->fetch_assoc()): ?>
                                    <div class="role-card <?php echo $role['is_system'] ? 'system-role' : ''; ?>">
                                        <div class="role-header">
                                            <div>
                                                <div class="role-name"><?php echo htmlspecialchars($role['role_name']); ?></div>
                                                <span class="role-badge badge-<?php echo $role['is_system'] ? 'system' : 'custom'; ?>">
                                                    <?php echo $role['is_system'] ? 'System Role' : 'Custom Role'; ?>
                                                </span>
                                            </div>
                                        </div>
                                        
                                        <div class="role-description">
                                            <?php echo htmlspecialchars($role['description'] ?: 'No description provided'); ?>
                                        </div>
                                        
                                        <div class="role-stats">
                                            <div class="stat-item">
                                                <div class="stat-value"><?php echo $role['user_count']; ?></div>
                                                <div class="stat-label">Users</div>
                                            </div>
                                            <div class="stat-item">
                                                <div class="stat-value"><?php echo $role['permission_count']; ?></div>
                                                <div class="stat-label">Permissions</div>
                                            </div>
                                        </div>
                                        
                                        <?php if ($role['user_names']): ?>
                                        <div class="role-users">
                                            <strong>Users:</strong> <?php echo htmlspecialchars($role['user_names']); ?>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <div class="role-actions">
                                            <?php if (!$role['is_system']): ?>
                                            <button onclick="editRole(<?php echo htmlspecialchars(json_encode($role)); ?>)" 
                                                    class="btn-sm btn-warning">
                                                <i class="ph-pencil"></i> Edit
                                            </button>
                                            <?php endif; ?>
                                            <button onclick="viewRolePermissions(<?php echo $role['role_id']; ?>, '<?php echo htmlspecialchars($role['role_name']); ?>')" 
                                                    class="btn-sm btn-info">
                                                <i class="ph-eye"></i> View Permissions
                                            </button>
                                        </div>
                                    </div>
                                    <?php endwhile; ?>
                                </div>
                            </div>
                            
                            <!-- Permissions Tab -->
                            <div id="permissions-tab" class="tab-pane">
                                <div class="permissions-table">
                                    <div class="table-header">
                                        <h3 class="table-title">Current Page Permissions</h3>
                                    </div>
                                    <table class="data-table">
                                        <thead>
                                            <tr>
                                                <th>Role</th>
                                                <th>Page Name</th>
                                                <th>Page Title</th>
                                                <th>Assigned Date</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php while($permission = $result_permissions->fetch_assoc()): ?>
                                            <tr>
                                                <td>
                                                    <span class="role-badge badge-<?php echo $permission['is_system'] ? 'system' : 'custom'; ?>">
                                                        <?php echo htmlspecialchars($permission['role_name']); ?>
                                                    </span>
                                                </td>
                                                <td style="font-family: 'Courier New', monospace; font-size: 0.8rem;">
                                                    <?php echo htmlspecialchars($permission['page_name']); ?>
                                                </td>
                                                <td style="font-weight: 600;">
                                                    <?php echo htmlspecialchars($available_pages[$permission['page_name']] ?? 'Unknown Page'); ?>
                                                </td>
                                                <td style="color: #64748b;">
                                                    <?php echo date('M j, Y', strtotime($permission['created_at'])); ?>
                                                </td>
                                                <td>
                                                    <?php if (!$permission['is_system']): ?>
                                                    <form method="POST" style="display: inline;" 
                                                          onsubmit="return confirm('Remove this permission?')">
                                                        <input type="hidden" name="action" value="remove_permission">
                                                        <input type="hidden" name="permission_id" value="<?php echo $permission['id']; ?>">
                                                        <button type="submit" class="btn-sm btn-danger">
                                                            <i class="ph-trash"></i> Remove
                                                        </button>
                                                    </form>
                                                    <?php else: ?>
                                                    <span style="font-size: 0.75rem; color: #64748b;">System Role</span>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                            <?php endwhile; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            
                            <!-- Add Permission Tab -->
                            <div id="add-permission-tab" class="tab-pane">
                                <div class="form-card">
                                    <h3 class="form-title">Add Page Permission</h3>
                                    
                                    <form method="POST">
                                        <input type="hidden" name="action" value="add_page_permission">
                                        
                                        <div class="form-group">
                                            <label class="form-label required">Select Role</label>
                                            <select name="permission_role_id" class="form-control" required>
                                                <option value="">Choose a role...</option>
                                                <?php 
                                                $result_roles->data_seek(0);
                                                while($role = $result_roles->fetch_assoc()): 
                                                    if (!$role['is_system']): // Only show custom roles
                                                ?>
                                                <option value="<?php echo $role['role_id']; ?>">
                                                    <?php echo htmlspecialchars($role['role_name']); ?>
                                                    (<?php echo $role['user_count']; ?> users)
                                                </option>
                                                <?php 
                                                    endif;
                                                endwhile; 
                                                ?>
                                            </select>
                                        </div>
                                        
                                        <div class="form-group">
                                            <label class="form-label required">Select Page</label>
                                            <select name="page_name" class="form-control" required>
                                                <option value="">Choose a page...</option>
                                                <?php foreach($available_pages as $page_file => $page_title): ?>
                                                <option value="<?php echo $page_file; ?>">
                                                    <?php echo htmlspecialchars($page_title); ?> (<?php echo $page_file; ?>)
                                                </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        
                                        <div style="background: #fffbeb; border: 1px solid #fbbf24; border-radius: 8px; padding: 1rem; margin-bottom: 1.5rem;">
                                            <div style="font-weight: 600; color: #92400e; margin-bottom: 0.5rem;">
                                                <i class="ph-warning"></i> Important Notes:
                                            </div>
                                            <ul style="margin: 0; color: #92400e; font-size: 0.875rem;">
                                                <li>Super Admin role has access to all pages automatically</li>
                                                <li>System roles (Super Admin, Manager, etc.) cannot be modified</li>
                                                <li>Users will only see menu items for pages they have permission to access</li>
                                                <li>Core pages (Dashboard, Profile, Logout) are always accessible</li>
                                            </ul>
                                        </div>
                                        
                                        <button type="submit" class="btn-success">
                                            <i class="ph-plus"></i> Add Permission
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Add Role Modal -->
    <div id="addRoleModal" class="modal-overlay">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">Add New Role</h3>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="add_role">
                
                <div class="form-group">
                    <label class="form-label required">Role Name</label>
                    <input type="text" name="role_name" class="form-control" 
                           placeholder="e.g., Senior Cashier" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Description</label>
                    <textarea name="description" class="form-control" rows="3" 
                              placeholder="Describe the role responsibilities and permissions"></textarea>
                </div>
                
                <div class="modal-actions">
                    <button type="button" onclick="closeModal('addRoleModal')" class="btn-cancel">Cancel</button>
                    <button type="submit" class="btn-success">Add Role</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Edit Role Modal -->
    <div id="editRoleModal" class="modal-overlay">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">Edit Role</h3>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="update_role">
                <input type="hidden" name="role_id" id="edit_role_id">
                
                <div class="form-group">
                    <label class="form-label required">Role Name</label>
                    <input type="text" name="edit_role_name" id="edit_role_name" class="form-control" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Description</label>
                    <textarea name="edit_description" id="edit_description" class="form-control" rows="3"></textarea>
                </div>
                
                <div class="modal-actions">
                    <button type="button" onclick="closeModal('editRoleModal')" class="btn-cancel">Cancel</button>
                    <button type="submit" class="btn-success">Update Role</button>
                </div>
            </form>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <script>
        // Tab functionality
        function switchTab(tabName) {
            // Hide all tab panes
            document.querySelectorAll('.tab-pane').forEach(pane => {
                pane.classList.remove('active');
            });
            
            // Remove active class from all tab buttons
            document.querySelectorAll('.tab-button').forEach(button => {
                button.classList.remove('active');
            });
            
            // Show selected tab and activate button
            document.getElementById(tabName + '-tab').classList.add('active');
            event.target.classList.add('active');
        }
        
        // Modal functions
        function openAddRoleModal() {
            document.getElementById('addRoleModal').style.display = 'flex';
        }
        
        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }
        
        function editRole(role) {
            document.getElementById('edit_role_id').value = role.role_id;
            document.getElementById('edit_role_name').value = role.role_name;
            document.getElementById('edit_description').value = role.description || '';
            
            document.getElementById('editRoleModal').style.display = 'flex';
        }
        
        function viewRolePermissions(roleId, roleName) {
            // Switch to permissions tab and filter by role
            switchTab('permissions');
            
            // Highlight rows for this role
            document.querySelectorAll('.data-table tbody tr').forEach(row => {
                const roleCell = row.querySelector('td:first-child');
                if (roleCell && roleCell.textContent.includes(roleName)) {
                    row.style.background = '#fef3c7';
                    setTimeout(() => {
                        row.style.background = '';
                    }, 3000);
                }
            });
        }
        
        // Close modals when clicking outside
        document.addEventListener('click', function(e) {
            if (e.target.classList.contains('modal-overlay')) {
                e.target.style.display = 'none';
            }
        });
        
        // Initialize tabs
        document.addEventListener('DOMContentLoaded', function() {
            // Add click handlers to tab buttons
            document.querySelectorAll('.tab-button').forEach(button => {
                button.addEventListener('click', function() {
                    const tabName = this.textContent.toLowerCase().includes('roles') ? 'roles' : 
                                  this.textContent.toLowerCase().includes('permissions') ? 'permissions' : 
                                  'add-permission';
                    switchTab(tabName);
                });
            });
        });
    </script>
    
    <script src="assets/js/app.js"></script>
</body>
</html>