<?php
/**
 * Enterprise HRM ERP System - Permission Verification Script
 * Checks which modules/pages have permission checks implemented
 */

require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/check_admin_access.php';

// Check if user is Super Admin
startSession();

$roleCode = $_SESSION['role_code'] ?? '';
if (empty($roleCode) && isset($_SESSION['user_id'])) {
    try {
        $db = getDB();
        $stmt = $db->prepare("
            SELECT r.role_code 
            FROM users u
            INNER JOIN roles r ON u.role_id = r.role_id
            WHERE u.user_id = ?
        ");
        $stmt->execute([$_SESSION['user_id']]);
        $userRole = $stmt->fetch();
        if ($userRole && !empty($userRole['role_code'])) {
            $roleCode = $userRole['role_code'];
            $_SESSION['role_code'] = $roleCode;
        }
    } catch (Exception $e) {
        error_log("Error loading role_code: " . $e->getMessage());
    }
}

if (strtolower($roleCode) !== 'super_admin') {
    $_SESSION['error'] = 'Only Super Admin can access permission verification.';
    header('Location: ' . BASE_URL . '/dashboard.php');
    exit;
}

$pageTitle = 'Permission Verification';
$currentModule = 'settings';

// Scan modules directory for PHP files
$modulesDir = __DIR__ . '/../modules';
$moduleFiles = [];
$permissionChecks = [];

if (is_dir($modulesDir)) {
    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($modulesDir, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::SELF_FIRST
    );
    
    foreach ($iterator as $file) {
        if ($file->isFile() && $file->getExtension() === 'php') {
            $relativePath = str_replace(__DIR__ . '/../', '', $file->getPathname());
            $content = file_get_contents($file->getPathname());
            
            // Check for permission-related functions
            $hasRequireLogin = strpos($content, 'requireLogin') !== false;
            $hasRequirePermission = strpos($content, 'requirePermission') !== false;
            $hasHasPermission = strpos($content, 'hasPermission') !== false;
            $hasRoleCheck = strpos($content, 'isSuperAdmin') !== false || 
                           strpos($content, 'isHRAdmin') !== false || 
                           strpos($content, 'isEmployee') !== false;
            
            $moduleFiles[] = [
                'file' => $relativePath,
                'has_require_login' => $hasRequireLogin,
                'has_require_permission' => $hasRequirePermission,
                'has_has_permission' => $hasHasPermission,
                'has_role_check' => $hasRoleCheck,
                'has_any_check' => $hasRequireLogin || $hasRequirePermission || $hasHasPermission || $hasRoleCheck
            ];
        }
    }
}

// Get all permissions from database
try {
    $db = getDB();
    $stmt = $db->prepare("
        SELECT permission_code, permission_name, permission_module
        FROM permissions
        ORDER BY permission_module, permission_code
    ");
    $stmt->execute();
    $allPermissions = $stmt->fetchAll();
    
    // Group by module
    $permissionsByModule = [];
    foreach ($allPermissions as $perm) {
        $module = $perm['permission_module'];
        if (!isset($permissionsByModule[$module])) {
            $permissionsByModule[$module] = [];
        }
        $permissionsByModule[$module][] = $perm;
    }
    
} catch (Exception $e) {
    error_log("Error loading permissions: " . $e->getMessage());
    $allPermissions = [];
    $permissionsByModule = [];
}

include __DIR__ . '/../includes/header.php';
?>

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Permission Verification Report</h2>
        <div style="display: flex; gap: 10px;">
            <a href="<?php echo BASE_URL; ?>/admin/role_management_dashboard.php" class="btn btn-secondary">Back to Dashboard</a>
            <a href="<?php echo BASE_URL; ?>/admin/roles.php" class="btn btn-secondary">Role Management</a>
        </div>
    </div>
    
    <!-- Summary -->
    <div style="margin-top: 20px; padding: 20px; background: #f8fafc; border-radius: 8px;">
        <h3 style="margin-bottom: 15px;">Summary</h3>
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px;">
            <div>
                <div style="font-size: 24px; font-weight: bold; color: var(--primary-color);">
                    <?php echo count($moduleFiles); ?>
                </div>
                <div style="font-size: 14px; color: var(--text-secondary);">Total PHP Files Scanned</div>
            </div>
            <div>
                <div style="font-size: 24px; font-weight: bold; color: #10b981;">
                    <?php echo count(array_filter($moduleFiles, function($f) { return $f['has_any_check']; })); ?>
                </div>
                <div style="font-size: 14px; color: var(--text-secondary);">Files with Permission Checks</div>
            </div>
            <div>
                <div style="font-size: 24px; font-weight: bold; color: #ef4444;">
                    <?php echo count(array_filter($moduleFiles, function($f) { return !$f['has_any_check']; })); ?>
                </div>
                <div style="font-size: 14px; color: var(--text-secondary);">Files Without Checks</div>
            </div>
            <div>
                <div style="font-size: 24px; font-weight: bold; color: var(--primary-color);">
                    <?php echo count($allPermissions); ?>
                </div>
                <div style="font-size: 14px; color: var(--text-secondary);">Total Permissions</div>
            </div>
        </div>
    </div>
    
    <!-- Files Without Permission Checks -->
    <div style="margin-top: 30px;">
        <h3 style="margin-bottom: 15px; color: #ef4444;">⚠️ Files Without Permission Checks</h3>
        <?php 
        $filesWithoutChecks = array_filter($moduleFiles, function($f) { return !$f['has_any_check']; });
        if (count($filesWithoutChecks) > 0): 
        ?>
        <div style="max-height: 400px; overflow-y: auto;">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>File Path</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($filesWithoutChecks as $file): ?>
                    <tr>
                        <td>
                            <code style="font-size: 12px;"><?php echo htmlspecialchars($file['file']); ?></code>
                        </td>
                        <td>
                            <span class="status-badge" style="background: #fee2e2; color: #991b1b;">
                                No Permission Check
                            </span>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php else: ?>
        <div class="table-empty">
            <div class="table-empty-icon">✅</div>
            <div class="table-empty-message">All files have permission checks!</div>
        </div>
        <?php endif; ?>
    </div>
    
    <!-- Files With Permission Checks -->
    <div style="margin-top: 30px;">
        <h3 style="margin-bottom: 15px; color: #10b981;">✅ Files With Permission Checks</h3>
        <?php 
        $filesWithChecks = array_filter($moduleFiles, function($f) { return $f['has_any_check']; });
        if (count($filesWithChecks) > 0): 
        ?>
        <div style="max-height: 400px; overflow-y: auto;">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>File Path</th>
                        <th>requireLogin</th>
                        <th>requirePermission</th>
                        <th>hasPermission</th>
                        <th>Role Check</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($filesWithChecks as $file): ?>
                    <tr>
                        <td>
                            <code style="font-size: 12px;"><?php echo htmlspecialchars($file['file']); ?></code>
                        </td>
                        <td style="text-align: center;">
                            <?php if ($file['has_require_login']): ?>
                            <span style="color: #10b981;">✓</span>
                            <?php else: ?>
                            <span style="color: #d1d5db;">-</span>
                            <?php endif; ?>
                        </td>
                        <td style="text-align: center;">
                            <?php if ($file['has_require_permission']): ?>
                            <span style="color: #10b981;">✓</span>
                            <?php else: ?>
                            <span style="color: #d1d5db;">-</span>
                            <?php endif; ?>
                        </td>
                        <td style="text-align: center;">
                            <?php if ($file['has_has_permission']): ?>
                            <span style="color: #10b981;">✓</span>
                            <?php else: ?>
                            <span style="color: #d1d5db;">-</span>
                            <?php endif; ?>
                        </td>
                        <td style="text-align: center;">
                            <?php if ($file['has_role_check']): ?>
                            <span style="color: #10b981;">✓</span>
                            <?php else: ?>
                            <span style="color: #d1d5db;">-</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    </div>
    
    <!-- Available Permissions -->
    <div style="margin-top: 30px;">
        <h3 style="margin-bottom: 15px;">Available Permissions by Module</h3>
        <?php if (count($permissionsByModule) > 0): ?>
        <?php foreach ($permissionsByModule as $module => $permissions): ?>
        <div style="margin-bottom: 20px; padding: 15px; background: #f8fafc; border-radius: 8px;">
            <h4 style="margin-bottom: 10px; color: var(--primary-color);">
                <?php echo htmlspecialchars($module); ?> Module
                <span style="font-size: 14px; color: var(--text-secondary); font-weight: normal;">
                    (<?php echo count($permissions); ?> permissions)
                </span>
            </h4>
            <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 10px;">
                <?php foreach ($permissions as $perm): ?>
                <div style="padding: 10px; background: white; border-radius: 6px; border: 1px solid var(--border-color);">
                    <div style="font-weight: 600; font-size: 13px; color: var(--text-primary);">
                        <?php echo htmlspecialchars($perm['permission_code']); ?>
                    </div>
                    <div style="font-size: 12px; color: var(--text-secondary); margin-top: 5px;">
                        <?php echo htmlspecialchars($perm['permission_name']); ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endforeach; ?>
        <?php else: ?>
        <div class="table-empty">
            <div class="table-empty-icon">🔐</div>
            <div class="table-empty-message">No permissions found</div>
        </div>
        <?php endif; ?>
    </div>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>

