<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class PaymentMethodPermissionsSeeder extends Seeder
{
    public function run()
    {
        $permissions = [
            [
                'name' => 'view-payment-method',
                'display_name' => 'View Payment Method',
                'description' => 'View Payment Methods',
                'created_at' => now(),
                'updated_at' => now(),
            ],
            [
                'name' => 'create-payment-method',
                'display_name' => 'Create Payment Method',
                'description' => 'Create Payment Methods',
                'created_at' => now(),
                'updated_at' => now(),
            ],
            [
                'name' => 'edit-payment-method',
                'display_name' => 'Edit Payment Method',
                'description' => 'Edit Payment Methods',
                'created_at' => now(),
                'updated_at' => now(),
            ],
            [
                'name' => 'delete-payment-method',
                'display_name' => 'Delete Payment Method',
                'description' => 'Delete Payment Methods',
                'created_at' => now(),
                'updated_at' => now(),
            ],
        ];

        // Definir qué permisos tiene cada rol
        $rolePermissions = [
            'doctor' => ['view-payment-method'],
            'receptionist' => ['view-payment-method'],
            'admin' => array_column($permissions, 'name'),
            'root' => array_column($permissions, 'name')
        ];

        foreach ($permissions as $permission) {
            // Solo insertar si no existe
            if (!DB::table('permissions')->where('name', $permission['name'])->exists()) {
                $permissionId = DB::table('permissions')->insertGetId($permission);

                // Asignar a roles según la configuración
                $roles = DB::table('roles')->whereIn('name', array_keys($rolePermissions))->get();
                foreach ($roles as $role) {
                    // Verificar si este rol debe tener este permiso
                    if (in_array($permission['name'], $rolePermissions[$role->name])) {
                        if (!DB::table('permission_role')->where([
                            'permission_id' => $permissionId,
                            'role_id' => $role->id
                        ])->exists()) {
                            DB::table('permission_role')->insert([
                                'permission_id' => $permissionId,
                                'role_id' => $role->id
                            ]);
                        }
                    }
                }
            }
        }
    }
} 