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

echo "<h2>Permission Cleanup Script</h2>";

try {
    // Get all user types
    $stmt = $pdo->query("SELECT id, name, permissions FROM user_types");
    $userTypes = $stmt->fetchAll();
    
    echo "<h3>Before cleanup:</h3>";
    foreach ($userTypes as $userType) {
        $decoded = json_decode($userType['permissions'], true);
        $count = is_array($decoded) ? count($decoded) : 0;
        echo "ID {$userType['id']} - {$userType['name']}: {$count} permissions<br>";
    }
    
    echo "<h3>Cleaning up...</h3>";
    
    foreach ($userTypes as $userType) {
        $permissions = json_decode($userType['permissions'], true);
        
        if (!is_array($permissions)) {
            $permissions = [];
        }
        
        // Clean up permissions - ensure they're in flat format
        $cleanPermissions = [];
        foreach ($permissions as $key => $value) {
            if (is_bool($value) && $value === true) {
                $cleanPermissions[$key] = true;
            } elseif ($value === "1" || $value === 1) {
                $cleanPermissions[$key] = true;
            }
        }
        
        // Update with clean permissions
        $updateStmt = $pdo->prepare("UPDATE user_types SET permissions = ? WHERE id = ?");
        $updateStmt->execute([json_encode($cleanPermissions), $userType['id']]);
        
        echo "Cleaned ID {$userType['id']} - {$userType['name']}: " . count($cleanPermissions) . " permissions<br>";
    }
    
    echo "<h3>After cleanup:</h3>";
    $stmt = $pdo->query("SELECT id, name, permissions FROM user_types");
    $userTypes = $stmt->fetchAll();
    
    foreach ($userTypes as $userType) {
        $decoded = json_decode($userType['permissions'], true);
        $count = is_array($decoded) ? count($decoded) : 0;
        echo "ID {$userType['id']} - {$userType['name']}: {$count} permissions<br>";
    }
    
    echo "<p style='color: green;'><strong>Cleanup completed!</strong></p>";
    
} catch (Exception $e) {
    echo "<p style='color: red;'>Error: " . $e->getMessage() . "</p>";
}
?>
