<?php
session_start();
require_once 'bootstrap/db.php';
require_once 'app/Models/UserType.php';

echo "<h2>Permission Count Verification</h2>";

$userType = new UserType();
$userTypes = $userType->getAll();

echo "<table border='1' style='border-collapse: collapse; width: 100%; margin: 20px 0;'>";
echo "<tr style='background-color: #f8f9fa;'>";
echo "<th>ID</th><th>Name</th><th>Raw JSON Length</th><th>Array Count</th><th>True Permissions</th><th>Sample Keys</th>";
echo "</tr>";

foreach ($userTypes as $type) {
    $rawPermissions = null;
    
    // Get raw data from database
    $stmt = $GLOBALS['pdo']->prepare("SELECT permissions FROM user_types WHERE id = ?");
    $stmt->execute([$type['id']]);
    $raw = $stmt->fetch();
    if ($raw) {
        $rawPermissions = $raw['permissions'];
    }
    
    // Count different ways
    $jsonLength = strlen($rawPermissions ?? '');
    $arrayCount = is_array($type['permissions']) ? count($type['permissions']) : 0;
    
    // Count only "true" permissions
    $trueCount = 0;
    $sampleKeys = [];
    if (is_array($type['permissions'])) {
        foreach ($type['permissions'] as $key => $value) {
            if ($value === true) {
                $trueCount++;
                if (count($sampleKeys) < 3) {
                    $sampleKeys[] = $key;
                }
            }
        }
    }
    
    echo "<tr>";
    echo "<td>{$type['id']}</td>";
    echo "<td>{$type['name']}</td>";
    echo "<td>{$jsonLength}</td>";
    echo "<td>{$arrayCount}</td>";
    echo "<td style='font-weight: bold; color: " . ($trueCount > 0 ? 'green' : 'red') . ";'>{$trueCount}</td>";
    echo "<td style='font-size: 0.8em;'>" . implode(', ', $sampleKeys) . "</td>";
    echo "</tr>";
}

echo "</table>";

echo "<h3>Raw JSON Data:</h3>";
foreach ($userTypes as $type) {
    $stmt = $GLOBALS['pdo']->prepare("SELECT permissions FROM user_types WHERE id = ?");
    $stmt->execute([$type['id']]);
    $raw = $stmt->fetch();
    
    echo "<h4>ID {$type['id']} - {$type['name']}:</h4>";
    echo "<pre style='background: #f8f9fa; padding: 10px; border-radius: 5px; overflow-wrap: break-word;'>";
    echo htmlspecialchars($raw['permissions'] ?? 'NULL');
    echo "</pre>";
    
    // Try to decode and show structure
    $decoded = json_decode($raw['permissions'] ?? '{}', true);
    if (is_array($decoded)) {
        echo "<p><strong>Decoded structure:</strong></p>";
        echo "<pre style='background: #e9ecef; padding: 10px; border-radius: 5px;'>";
        print_r($decoded);
        echo "</pre>";
    }
}
?>
