<?php
/**
 * ============================================================================
 * admin/role-permissions.php - Role Permissions Management
 * Manage permissions for each role with auto-sync capabilities
 * ============================================================================
 */

require_once __DIR__ . '/includes/base.php';

// Check permission
if (!hasAdminPermission('manage_roles')) {
    setFlashMessage('Access denied. Role management permission required.', 'error');
    header('Location: ' . APP_URL . '/admin/index.php');
    exit();
}

$breadcrumbs = [
    ['title' => 'Roles & Permissions', 'url' => APP_URL . '/admin/roles.php'],
    ['title' => 'Permission Management', 'url' => '']
];

// Fetch all roles with permission counts
try {
    $sql = "SELECT 
                ar.*,
                COUNT(DISTINCT rp.id) as permissions_count,
                (SELECT COUNT(*) FROM admin_permissions) as total_permissions
            FROM admin_roles ar
            LEFT JOIN role_permissions rp ON ar.id = rp.role_id
            GROUP BY ar.id
            ORDER BY ar.role_level DESC, ar.role_name";
    $stmt = $db->query($sql);
    $roles = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Fetch all permissions grouped by category
    $sql = "SELECT * FROM admin_permissions ORDER BY permission_category, permission_name";
    $stmt = $db->query($sql);
    $all_permissions = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Group permissions by category
    $permissions_by_category = [];
    foreach ($all_permissions as $perm) {
        $permissions_by_category[$perm['permission_category']][] = $perm;
    }
    
    // Get recent permission changes
    $sql = "SELECT 
                aal.*,
                u.full_name as admin_name,
                ar.role_name
            FROM admin_activity_log aal
            LEFT JOIN users u ON aal.admin_id = u.id
            LEFT JOIN role_permissions rp ON aal.affected_record_id = rp.id
            LEFT JOIN admin_roles ar ON rp.role_id = ar.id
            WHERE aal.action_type IN ('grant_permission', 'revoke_permission', 'sync_permissions', 'auto_permission_grant')
            ORDER BY aal.created_at DESC
            LIMIT 20";
    $stmt = $db->query($sql);
    $recent_changes = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (PDOException $e) {
    logError('Role permissions fetch error: ' . $e->getMessage());
    $roles = [];
    $permissions_by_category = [];
    $recent_changes = [];
}

renderAdminHeader('Role Permissions Management', $breadcrumbs);
?>

<style>
.permission-matrix {
    overflow-x: auto;
}
.permission-matrix table {
    min-width: 800px;
}
.permission-cell {
    text-align: center;
    vertical-align: middle;
}
.permission-checkbox {
    width: 20px;
    height: 20px;
    cursor: pointer;
}
.role-column {
    min-width: 100px;
}
.sync-status {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.75rem;
    font-weight: 600;
}
.sync-status.synced {
    background: #d1fae5;
    color: #065f46;
}
.sync-status.outdated {
    background: #fef3c7;
    color: #92400e;
}
.category-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    font-weight: 600;
    padding: 12px;
    position: sticky;
    top: 0;
    z-index: 10;
}
</style>

<!-- Page Header -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-1 fw-bold">
            <i class="bi bi-diagram-3 me-2"></i>Role Permissions Management
        </h2>
        <p class="text-muted mb-0">Assign and manage permissions for admin roles</p>
    </div>
    <div class="d-flex gap-2">
        <button class="btn btn-primary" onclick="syncAllPermissions()">
            <i class="bi bi-arrow-repeat me-2"></i>Sync All Roles
        </button>
        <button class="btn btn-outline-primary" onclick="exportPermissions()">
            <i class="bi bi-download me-2"></i>Export Matrix
        </button>
    </div>
</div>

<!-- Role Summary Cards -->
<div class="row mb-4">
    <?php foreach ($roles as $role): 
        $coverage = $role['total_permissions'] > 0 ? 
            round(($role['permissions_count'] / $role['total_permissions']) * 100) : 0;
        $status_class = $coverage >= 90 ? 'success' : ($coverage >= 50 ? 'warning' : 'danger');
    ?>
    <div class="col-lg-3 col-md-6 mb-3">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start mb-3">
                    <div>
                        <h6 class="mb-1"><?php echo htmlspecialchars($role['role_name']); ?></h6>
                        <small class="text-muted">Level <?php echo $role['role_level']; ?></small>
                    </div>
                    <span class="badge bg-<?php echo $status_class; ?>">
                        <?php echo $coverage; ?>%
                    </span>
                </div>
                <div class="mb-2">
                    <div class="progress" style="height: 8px;">
                        <div class="progress-bar bg-<?php echo $status_class; ?>" 
                             style="width: <?php echo $coverage; ?>%"></div>
                    </div>
                </div>
                <div class="d-flex justify-content-between align-items-center">
                    <small class="text-muted">
                        <?php echo $role['permissions_count']; ?> / <?php echo $role['total_permissions']; ?> permissions
                    </small>
                    <button class="btn btn-sm btn-outline-primary" 
                            onclick="syncRole(<?php echo $role['id']; ?>)">
                        <i class="bi bi-arrow-repeat"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<!-- Tabs -->
<ul class="nav nav-tabs mb-4">
    <li class="nav-item">
        <a class="nav-link active" data-bs-toggle="tab" href="#matrix">
            <i class="bi bi-grid-3x3 me-2"></i>Permission Matrix
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link" data-bs-toggle="tab" href="#changes">
            <i class="bi bi-clock-history me-2"></i>Recent Changes
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link" data-bs-toggle="tab" href="#bulk">
            <i class="bi bi-lightning me-2"></i>Bulk Operations
        </a>
    </li>
</ul>

<div class="tab-content">
    <!-- Permission Matrix Tab -->
    <div class="tab-pane fade show active" id="matrix">
        <div class="card border-0 shadow-sm">
            <div class="card-body p-0">
                <div class="permission-matrix">
                    <table class="table table-bordered mb-0">
                        <thead>
                            <tr>
                                <th style="min-width: 250px; position: sticky; left: 0; background: white; z-index: 11;">
                                    Permission
                                </th>
                                <?php foreach ($roles as $role): ?>
                                <th class="role-column permission-cell">
                                    <div class="fw-bold"><?php echo htmlspecialchars($role['role_name']); ?></div>
                                    <small class="text-muted">L<?php echo $role['role_level']; ?></small>
                                </th>
                                <?php endforeach; ?>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($permissions_by_category as $category => $permissions): ?>
                            <tr>
                                <td colspan="<?php echo count($roles) + 1; ?>" class="category-header">
                                    <i class="bi bi-folder me-2"></i><?php echo strtoupper($category); ?>
                                </td>
                            </tr>
                            <?php foreach ($permissions as $perm): ?>
                            <tr data-permission-id="<?php echo $perm['id']; ?>">
                                <td style="position: sticky; left: 0; background: white; z-index: 1;">
                                    <div class="fw-semibold"><?php echo htmlspecialchars($perm['permission_name']); ?></div>
                                    <small class="text-muted"><?php echo htmlspecialchars($perm['permission_description']); ?></small>
                                    <br><small class="badge bg-secondary"><?php echo $perm['permission_key']; ?></small>
                                </td>
                                <?php foreach ($roles as $role): 
                                    // Check if role has this permission
                                    $sql = "SELECT COUNT(*) as has_perm FROM role_permissions 
                                            WHERE role_id = ? AND permission_id = ?";
                                    $stmt = $db->prepare($sql);
                                    $stmt->execute([$role['id'], $perm['id']]);
                                    $has_permission = $stmt->fetch(PDO::FETCH_ASSOC)['has_perm'] > 0;
                                    
                                    // Determine if checkbox should be disabled
                                    $is_disabled = ($role['role_level'] >= 10 && $perm['permission_key'] === 'full_access') ? 'disabled' : '';
                                ?>
                                <td class="permission-cell">
                                    <input type="checkbox" 
                                           class="permission-checkbox form-check-input" 
                                           data-role-id="<?php echo $role['id']; ?>"
                                           data-permission-id="<?php echo $perm['id']; ?>"
                                           data-permission-key="<?php echo $perm['permission_key']; ?>"
                                           <?php echo $has_permission ? 'checked' : ''; ?>
                                           <?php echo $is_disabled; ?>
                                           onchange="togglePermission(this)">
                                </td>
                                <?php endforeach; ?>
                            </tr>
                            <?php endforeach; ?>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Recent Changes Tab -->
    <div class="tab-pane fade" id="changes">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white py-3">
                <h5 class="mb-0 fw-bold">
                    <i class="bi bi-clock-history me-2"></i>Recent Permission Changes
                </h5>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>Timestamp</th>
                                <th>Action</th>
                                <th>Description</th>
                                <th>Admin</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($recent_changes as $change): ?>
                            <tr>
                                <td>
                                    <small><?php echo formatDate($change['created_at']); ?></small>
                                </td>
                                <td>
                                    <span class="badge bg-<?php 
                                        echo $change['action_type'] === 'grant_permission' ? 'success' : 
                                            ($change['action_type'] === 'revoke_permission' ? 'danger' : 'info');
                                    ?>">
                                        <?php echo str_replace('_', ' ', $change['action_type']); ?>
                                    </span>
                                </td>
                                <td><?php echo htmlspecialchars($change['action_description']); ?></td>
                                <td>
                                    <small class="text-muted">
                                        <?php echo htmlspecialchars($change['admin_name'] ?? 'System'); ?>
                                    </small>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Bulk Operations Tab -->
    <div class="tab-pane fade" id="bulk">
        <div class="row">
            <div class="col-md-6 mb-4">
                <div class="card border-0 shadow-sm">
                    <div class="card-header bg-white py-3">
                        <h5 class="mb-0 fw-bold">
                            <i class="bi bi-lightning-fill me-2"></i>Quick Actions
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="d-grid gap-3">
                            <button class="btn btn-outline-primary text-start" onclick="grantAllToRole()">
                                <i class="bi bi-check-all me-2"></i>
                                <strong>Grant All Permissions to Role</strong>
                                <br><small class="text-muted">Select a role and grant all available permissions</small>
                            </button>
                            
                            <button class="btn btn-outline-warning text-start" onclick="grantCategoryToRole()">
                                <i class="bi bi-folder-check me-2"></i>
                                <strong>Grant Category to Role</strong>
                                <br><small class="text-muted">Grant all permissions in a specific category</small>
                            </button>
                            
                            <button class="btn btn-outline-info text-start" onclick="copyRolePermissions()">
                                <i class="bi bi-files me-2"></i>
                                <strong>Copy Permissions from Another Role</strong>
                                <br><small class="text-muted">Duplicate permissions from one role to another</small>
                            </button>
                            
                            <button class="btn btn-outline-danger text-start" onclick="revokeAllFromRole()">
                                <i class="bi bi-x-circle me-2"></i>
                                <strong>Revoke All Permissions</strong>
                                <br><small class="text-muted">Remove all permissions from a role (except view_dashboard)</small>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-6 mb-4">
                <div class="card border-0 shadow-sm">
                    <div class="card-header bg-white py-3">
                        <h5 class="mb-0 fw-bold">
                            <i class="bi bi-shield-check me-2"></i>Permission Templates
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-info">
                            <i class="bi bi-info-circle me-2"></i>
                            <strong>Permission Templates</strong><br>
                            Apply pre-configured permission sets based on common role types.
                        </div>
                        
                        <div class="d-grid gap-2">
                            <button class="btn btn-outline-secondary" onclick="applyTemplate('content_manager')">
                                <i class="bi bi-file-text me-2"></i>Content Manager Template
                            </button>
                            <button class="btn btn-outline-secondary" onclick="applyTemplate('user_moderator')">
                                <i class="bi bi-people me-2"></i>User Moderator Template
                            </button>
                            <button class="btn btn-outline-secondary" onclick="applyTemplate('data_analyst')">
                                <i class="bi bi-graph-up me-2"></i>Data Analyst Template
                            </button>
                            <button class="btn btn-outline-secondary" onclick="applyTemplate('it_admin')">
                                <i class="bi bi-hdd-rack me-2"></i>IT Administrator Template
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Toggle individual permission
function togglePermission(checkbox) {
    const roleId = $(checkbox).data('role-id');
    const permissionId = $(checkbox).data('permission-id');
    const isGranting = $(checkbox).is(':checked');
    
    $.ajax({
        url: APP_URL + '/api/admin.php',
        method: 'POST',
        data: {
            action: isGranting ? 'grant_permission' : 'revoke_permission',
            role_id: roleId,
            permission_id: permissionId
        },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                showToast(response.message, 'success');
            } else {
                showToast(response.message, 'error');
                $(checkbox).prop('checked', !isGranting);
            }
        },
        error: function() {
            showToast('Connection error', 'error');
            $(checkbox).prop('checked', !isGranting);
        }
    });
}

// Sync all roles
function syncAllPermissions() {
    Swal.fire({
        title: 'Sync All Role Permissions',
        text: 'This will update permissions for all roles based on their levels. Continue?',
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Yes, Sync All',
        confirmButtonColor: '#059669'
    }).then((result) => {
        if (result.isConfirmed) {
            showLoading();
            $.post(APP_URL + '/api/admin.php', {
                action: 'sync_all_role_permissions'
            }, function(response) {
                hideLoading();
                if (response.success) {
                    Swal.fire('Success!', response.message, 'success')
                        .then(() => location.reload());
                } else {
                    showToast(response.message, 'error');
                }
            }).fail(function() {
                hideLoading();
                showToast('Connection error', 'error');
            });
        }
    });
}

// Sync single role
function syncRole(roleId) {
    showLoading();
    $.post(APP_URL + '/api/admin.php', {
        action: 'sync_role_permissions',
        role_id: roleId
    }, function(response) {
        hideLoading();
        if (response.success) {
            showToast(response.message, 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            showToast(response.message, 'error');
        }
    });
}

// Grant all permissions to a role
function grantAllToRole() {
    Swal.fire({
        title: 'Grant All Permissions',
        input: 'select',
        inputOptions: {
            <?php foreach ($roles as $role): ?>
            '<?php echo $role['id']; ?>': '<?php echo htmlspecialchars($role['role_name']); ?>',
            <?php endforeach; ?>
        },
        inputPlaceholder: 'Select a role',
        showCancelButton: true,
        confirmButtonText: 'Grant All'
    }).then((result) => {
        if (result.isConfirmed && result.value) {
            showLoading();
            $.post(APP_URL + '/api/admin.php', {
                action: 'grant_all_permissions',
                role_id: result.value
            }, function(response) {
                hideLoading();
                if (response.success) {
                    showToast(response.message, 'success');
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showToast(response.message, 'error');
                }
            });
        }
    });
}

// Export permissions matrix
function exportPermissions() {
    window.location.href = APP_URL + '/admin/export-permissions-matrix.php';
}
</script>

<?php renderAdminFooter(); ?>