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

echo "<h2>Comprehensive Permission Repair and Verification</h2>";

// Step 1: Get all user types
$stmt = $pdo->query("SELECT * FROM user_types ORDER BY id");
$userTypes = $stmt->fetchAll();

echo "<h3>Step 1: Current State</h3>";
echo "<table border='1' style='border-collapse: collapse; width: 100%;'>";
echo "<tr><th>ID</th><th>Name</th><th>Raw JSON</th><th>Issues Found</th></tr>";

$issues = [];
foreach ($userTypes as $userType) {
    $userIssues = [];
    $permissions = json_decode($userType['permissions'], true);
    
    if (json_last_error() !== JSON_ERROR_NONE) {
        $userIssues[] = "JSON decode error";
    }
    
    if (!is_array($permissions)) {
        $userIssues[] = "Not an array";
        $permissions = [];
    }
    
    // Check for nested structures
    foreach ($permissions as $key => $value) {
        if (is_array($value)) {
            $userIssues[] = "Nested array detected: $key";
        }
        if (!is_bool($value) && $value !== true && $value !== false) {
            $userIssues[] = "Non-boolean value: $key = " . var_export($value, true);
        }
    }
    
    echo "<tr>";
    echo "<td>{$userType['id']}</td>";
    echo "<td>{$userType['name']}</td>";
    echo "<td style='font-family: monospace; font-size: 0.8em; max-width: 300px; overflow-wrap: break-word;'>" . 
         htmlspecialchars(substr($userType['permissions'], 0, 100)) . 
         (strlen($userType['permissions']) > 100 ? '...' : '') . "</td>";
    echo "<td style='color: " . (empty($userIssues) ? 'green' : 'red') . ";'>" . 
         (empty($userIssues) ? 'OK' : implode(', ', $userIssues)) . "</td>";
    echo "</tr>";
    
    if (!empty($userIssues)) {
        $issues[$userType['id']] = $userIssues;
    }
}
echo "</table>";

// Step 2: Fix issues
if (!empty($issues)) {
    echo "<h3>Step 2: Fixing Issues</h3>";
    
    foreach ($issues as $userId => $userIssues) {
        $stmt = $pdo->prepare("SELECT * FROM user_types WHERE id = ?");
        $stmt->execute([$userId]);
        $userType = $stmt->fetch();
        
        echo "<h4>Fixing User Type: {$userType['name']} (ID: $userId)</h4>";
        
        $permissions = json_decode($userType['permissions'], true);
        if (!is_array($permissions)) {
            $permissions = [];
        }
        
        // Flatten nested permissions and ensure boolean values
        $flatPermissions = [];
        flattenPermissions($permissions, $flatPermissions);
        
        // Update the database
        $updateStmt = $pdo->prepare("UPDATE user_types SET permissions = ? WHERE id = ?");
        $result = $updateStmt->execute([json_encode($flatPermissions), $userId]);
        
        if ($result) {
            echo "<p style='color: green;'>✓ Fixed {$userType['name']} - " . count($flatPermissions) . " permissions</p>";
        } else {
            echo "<p style='color: red;'>✗ Failed to fix {$userType['name']}</p>";
        }
    }
} else {
    echo "<h3>Step 2: No Issues Found</h3>";
    echo "<p style='color: green;'>All user types have properly formatted permissions!</p>";
}

// Step 3: Final verification
echo "<h3>Step 3: Final Verification</h3>";
$stmt = $pdo->query("SELECT * FROM user_types ORDER BY id");
$userTypes = $stmt->fetchAll();

echo "<table border='1' style='border-collapse: collapse; width: 100%;'>";
echo "<tr><th>ID</th><th>Name</th><th>Permission Count</th><th>Status</th></tr>";

foreach ($userTypes as $userType) {
    $permissions = json_decode($userType['permissions'], true);
    $trueCount = 0;
    
    if (is_array($permissions)) {
        foreach ($permissions as $key => $value) {
            if ($value === true) {
                $trueCount++;
            }
        }
    }
    
    $status = is_array($permissions) ? 'OK' : 'ERROR';
    $statusColor = $status === 'OK' ? 'green' : 'red';
    
    echo "<tr>";
    echo "<td>{$userType['id']}</td>";
    echo "<td>{$userType['name']}</td>";
    echo "<td style='font-weight: bold;'>{$trueCount}</td>";
    echo "<td style='color: {$statusColor};'>{$status}</td>";
    echo "</tr>";
}
echo "</table>";

// Helper function to flatten nested permissions
function flattenPermissions($permissions, &$result, $prefix = '') {
    foreach ($permissions as $key => $value) {
        $fullKey = $prefix ? $prefix . '.' . $key : $key;
        
        if (is_array($value)) {
            flattenPermissions($value, $result, $fullKey);
        } else {
            // Convert to boolean
            $result[$fullKey] = (bool)$value;
        }
    }
}

echo "<p style='margin-top: 20px; padding: 15px; background-color: #d4edda; border: 1px solid #c3e6cb; border-radius: 5px;'>";
echo "<strong>Permission repair completed!</strong> All user types now have properly formatted permissions.";
echo "</p>";
?>
