<?php
// Setup default admin user type with all permissions
require_once '../bootstrap/db.php';
require_once '../app/Models/UserType.php';
require_once '../app/Models/PermissionScanner.php';

try {
    $userTypeModel = new UserType();
    $permissionScanner = new PermissionScanner();
    
    // Generate all available permissions
    $allPermissions = $permissionScanner->generatePermissions();
    
    // Create permissions array with all permissions set to true
    $adminPermissions = [];
    foreach ($allPermissions as $permission) {
        $adminPermissions[$permission['key']] = true;
    }
    
    // Check if admin user type already exists
    $existingAdminType = $pdo->query("SELECT * FROM user_types WHERE name = 'Administrator'")->fetch();
    
    if (!$existingAdminType) {
        // Create admin user type
        $adminData = [
            'name' => 'Administrator',
            'description' => 'Full system administrator with all permissions',
            'permissions' => json_encode($adminPermissions),
            'color' => '#dc3545',
            'is_active' => 1
        ];
        
        if ($userTypeModel->create($adminData)) {
            echo "✓ Administrator user type created with " . count($allPermissions) . " permissions<br>";
            $adminTypeId = $pdo->lastInsertId();
        } else {
            echo "✗ Failed to create administrator user type<br>";
            exit;
        }
    } else {
        // Update existing admin type with new permissions
        $adminTypeId = $existingAdminType['id'];
        $currentPermissions = json_decode($existingAdminType['permissions'] ?? '{}', true);
        
        // Merge with new permissions
        $updatedPermissions = array_merge($currentPermissions, $adminPermissions);
        
        $updateData = [
            'name' => 'Administrator',
            'description' => 'Full system administrator with all permissions',
            'permissions' => json_encode($updatedPermissions),
            'color' => '#dc3545',
            'is_active' => 1
        ];
        
        if ($userTypeModel->update($adminTypeId, $updateData)) {
            echo "✓ Administrator user type updated with " . count($allPermissions) . " permissions<br>";
        } else {
            echo "✗ Failed to update administrator user type<br>";
        }
    }
    
    // Update admin users to use the admin user type
    $stmt = $pdo->prepare("UPDATE users SET user_type_id = ? WHERE role = 'admin' AND user_type_id IS NULL");
    $stmt->execute([$adminTypeId]);
    $updatedUsers = $stmt->rowCount();
    
    if ($updatedUsers > 0) {
        echo "✓ Updated {$updatedUsers} admin users with Administrator user type<br>";
    }
    
    // Create a regular user type
    $existingUserType = $pdo->query("SELECT * FROM user_types WHERE name = 'Regular User'")->fetch();
    
    if (!$existingUserType) {
        $userPermissions = [];
        foreach ($allPermissions as $permission) {
            // Give regular users basic view permissions only
            if (strpos($permission['key'], '_view') !== false) {
                $userPermissions[$permission['key']] = true;
            } else {
                $userPermissions[$permission['key']] = false;
            }
        }
        
        $userData = [
            'name' => 'Regular User',
            'description' => 'Standard user with basic view permissions',
            'permissions' => json_encode($userPermissions),
            'color' => '#28a745',
            'is_active' => 1
        ];
        
        if ($userTypeModel->create($userData)) {
            echo "✓ Regular User type created<br>";
            $userTypeId = $pdo->lastInsertId();
            
            // Update regular users to use the user type
            $stmt = $pdo->prepare("UPDATE users SET user_type_id = ? WHERE role = 'user' AND user_type_id IS NULL");
            $stmt->execute([$userTypeId]);
            $updatedRegularUsers = $stmt->rowCount();
            
            if ($updatedRegularUsers > 0) {
                echo "✓ Updated {$updatedRegularUsers} regular users with Regular User type<br>";
            }
        }
    }
    
    echo "<br><strong>Setup completed successfully!</strong><br>";
    echo "<a href='/samanta_crm/user-types'>→ Go to User Types Management</a><br>";
    echo "<a href='/samanta_crm/languages'>→ Go to Languages Management</a><br>";
    echo "<a href='/samanta_crm/dashboard'>→ Go to Dashboard</a>";
    
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}
?>
