<?php
// pages/app_functions_permissions.php
requireRole('admin');

// 1. Define App Functions
$app_functions = [
    'Dashboard' => 'Overview of recent activities, stats, and quick links.',
    'Attendance' => 'Track member attendance for services, including manual entry and metrics.',
    'Roster Management' => 'Manage service rosters, assign roles to members, and view monthly schedules.',
    'Reports' => 'Generate and export reports for attendance, punctuality, and service summaries.',
    'Member Management' => 'Add, edit, and manage detailed profiles for all members.',
    'User Management' => 'Manage system access, create user accounts, and assign roles.',
    'Settings' => 'Configure app-wide settings, dropdown options, and backup/restore database.',
    'Kiosk Mode' => 'Self-service interface for members to check in attendance.',
    'Public Calendar' => 'View-only calendar of upcoming services and events.'
];

// 2. Define Permissions Matrix
// Based on hierarchy in includes/functions.php
$permissions = [
    'admin' => [
        'level' => 100,
        'description' => 'Full System Access',
        'capabilities' => [
            'Access all pages',
            'Manage Users & Members',
            'Edit Roster & Attendance',
            'Configure Settings',
            'Backup/Restore Database'
        ]
    ],
    'coordinator' => [
        'level' => 80,
        'description' => 'Operational Lead',
        'capabilities' => [
            'View & Edit Roster',
            'View & Edit Attendance',
            'Manage Members',
            'Access Reports',
            'Cannot manage Users or System Settings'
        ]
    ],
    'roster_manager' => [
        'level' => 60,
        'description' => 'Roster Management',
        'capabilities' => [
            'View & Edit Roster',
            'View Assignments',
            'Cannot manage Members or Attendance Details',
            'Cannot access Reports (restricted)'
        ]
    ],
    'member' => [
        'level' => 40,
        'description' => 'Standard User',
        'capabilities' => [
            'View Roster',
            'View Own Profile',
            'Check-in via Kiosk',
            'No administrative access'
        ]
    ],
    'viewer' => [
        'level' => 20,
        'description' => 'Read-Only Access',
        'capabilities' => [
            'View Dashboard',
            'View Public Calendar',
            'No edit capabilities'
        ]
    ]
];

// 3. Fetch Users and their Roles
$users_list = $pdo->query("SELECT u.username, u.role, m.full_name 
                           FROM users u 
                           LEFT JOIN members m ON u.member_id = m.id 
                           ORDER BY u.role DESC, u.username ASC")->fetchAll();

?>

<h1>App Functions & Permissions Guide</h1>
<p class="mb-4">Overview of system capabilities, user roles, and current access rights.</p>

<div class="tabs">
    <button class="tab-btn active" onclick="openTab(event, 'Functions')">App Functions</button>
    <button class="tab-btn" onclick="openTab(event, 'Permissions')">Permissions Matrix</button>
    <button class="tab-btn" onclick="openTab(event, 'Users')">User Access</button>
</div>

<!-- Tab 1: App Functions -->
<div id="Functions" class="tab-content" style="display: block;">
    <div class="card">
        <h2>System Capabilities</h2>
        <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 20px; margin-top: 20px;">
            <?php foreach ($app_functions as $title => $desc): ?>
            <div style="border: 1px solid #444; border-radius: 8px; padding: 15px; background: rgba(255,255,255,0.05);">
                <h3 style="margin-top: 0; color: var(--primary-color);"><?php echo htmlspecialchars($title); ?></h3>
                <p style="margin-bottom: 0; color: #ccc;"><?php echo htmlspecialchars($desc); ?></p>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<!-- Tab 2: Permissions Matrix -->
<div id="Permissions" class="tab-content" style="display: none;">
    <div class="card">
        <h2>Role Capabilities</h2>
        <div class="table-responsive">
            <table class="table">
                <thead>
                    <tr>
                        <th>Role</th>
                        <th>Level</th>
                        <th>Description</th>
                        <th>Capabilities & Limitations</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($permissions as $role => $info): ?>
                    <tr>
                        <td style="font-weight: bold; text-transform: capitalize; color: var(--secondary-color);">
                            <?php echo $role; ?>
                        </td>
                        <td><?php echo $info['level']; ?></td>
                        <td><?php echo $info['description']; ?></td>
                        <td>
                            <ul style="margin: 0; padding-left: 20px; color: #ddd;">
                                <?php foreach ($info['capabilities'] as $cap): ?>
                                <li><?php echo $cap; ?></li>
                                <?php endforeach; ?>
                            </ul>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Tab 3: Users Access -->
<div id="Users" class="tab-content" style="display: none;">
    <div class="card">
        <h2>Current User Access Rights</h2>
        <p style="color: #888; margin-bottom: 20px;">List of all registered users and their effective permissions.</p>
        
        <div class="table-responsive">
            <table class="table">
                <thead>
                    <tr>
                        <th>Username</th>
                        <th>Linked Member</th>
                        <th>Access Role</th>
                        <th>Effective Permissions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($users_list as $user): 
                        $role_info = $permissions[$user['role']] ?? ['description' => 'Unknown', 'capabilities' => []];
                    ?>
                    <tr>
                        <td style="font-weight: bold;"><?php echo htmlspecialchars($user['username']); ?></td>
                        <td>
                            <?php if ($user['full_name']): ?>
                                <span style="background: rgba(255,255,255,0.1); padding: 2px 6px; border-radius: 4px; font-size: 0.9em;">
                                    <?php echo htmlspecialchars($user['full_name']); ?>
                                </span>
                            <?php else: ?>
                                <span style="color: #666;">-</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <span class="badge" style="background: var(--primary-color); text-transform: capitalize;">
                                <?php echo htmlspecialchars($user['role']); ?>
                            </span>
                        </td>
                        <td>
                            <small style="display: block; color: #aaa; margin-bottom: 4px;"><?php echo $role_info['description']; ?></small>
                            <span style="font-size: 0.85rem; color: #ccc;">
                                <?php echo implode(', ', array_slice($role_info['capabilities'], 0, 3)); ?>...
                            </span>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<style>
/* Simple Tab Styles */
.tabs {
    margin-bottom: 20px;
    border-bottom: 1px solid #444;
}
.tab-btn {
    background: none;
    border: none;
    color: #888;
    padding: 10px 20px;
    font-size: 1rem;
    cursor: pointer;
    border-bottom: 2px solid transparent;
    transition: all 0.3s ease;
}
.tab-btn:hover {
    color: #fff;
}
.tab-btn.active {
    color: var(--primary-color);
    border-bottom: 2px solid var(--primary-color);
}
.table th {
    text-align: left;
    padding: 12px;
    border-bottom: 1px solid #444;
    color: #888;
}
.table td {
    padding: 12px;
    border-bottom: 1px solid #333;
    vertical-align: top;
}
</style>

<script>
function openTab(evt, tabName) {
    var i, tabcontent, tablinks;
    tabcontent = document.getElementsByClassName("tab-content");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("tab-btn");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }
    document.getElementById(tabName).style.display = "block";
    evt.currentTarget.className += " active";
}
</script>
