<?php

require __DIR__.'/vendor/autoload.php';

$app = require_once __DIR__.'/bootstrap/app.php';

$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);

$kernel->bootstrap();

use App\Models\Permission;
use App\Models\UserRole;
use App\Models\UserRolePermission;

echo "Checking Permission...\n";
$permName = 'report_monthly_summary';
$permission = Permission::where('name', $permName)->first();

if (!$permission) {
    echo "Creating permission '$permName'...\n";
    $permission = Permission::create([
        'name' => $permName,
        'display_name' => 'Monthly Summary',
        'category' => 'Report'
    ]);
    echo "Permission created with ID: " . $permission->id . "\n";
} else {
    echo "Permission '$permName' already exists (ID: " . $permission->id . ").\n";
}

echo "Checking Admin Role Assignment...\n";
$adminRole = UserRole::where('id', 1)->first(); // Assuming ID 1 is Admin
if ($adminRole) {
    $hasPerm = UserRolePermission::where('role_id', $adminRole->id)
                                 ->where('permission_name', $permName)
                                 ->exists();

    if (!$hasPerm) {
        echo "Assigning permission to Admin role...\n";
        UserRolePermission::create([
            'role_id' => $adminRole->id,
            'permission_id' => $permission->id,
            'permission_name' => $permission->name,
            'name' => $adminRole->name
        ]);
        echo "Assigned.\n";
    } else {
        echo "Admin role already has this permission.\n";
    }
} else {
    echo "Admin role not found!\n";
}

echo "Done.\n";
