<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;

class CreatePaymentPermissions extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // Definir los permisos de pagos
        $permissions = [
            [
                'name' => 'view-payment',
                'display_name' => 'Ver Pagos',
                'description' => 'Permite ver los pagos registrados'
            ],
            [
                'name' => 'create-payment',
                'display_name' => 'Crear Pagos',
                'description' => 'Permite crear nuevos pagos'
            ],
            [
                'name' => 'edit-payment',
                'display_name' => 'Editar Pagos',
                'description' => 'Permite modificar pagos existentes'
            ],
            [
                'name' => 'view-payment-method',
                'display_name' => 'Ver Métodos de Pago',
                'description' => 'Permite ver los métodos de pago'
            ],
            [
                'name' => 'create-payment-method',
                'display_name' => 'Crear Métodos de Pago',
                'description' => 'Permite crear nuevos métodos de pago'
            ],
            [
                'name' => 'edit-payment-method',
                'display_name' => 'Editar Métodos de Pago',
                'description' => 'Permite modificar métodos de pago'
            ]
        ];

        // Insertar los permisos
        foreach ($permissions as $permission) {
            // Verificar si el permiso ya existe
            $exists = DB::table('permissions')
                ->where('name', $permission['name'])
                ->exists();

            if (!$exists) {
                DB::table('permissions')->insert($permission);
            }
        }

        // Asignar permisos a roles
        $roles = [
            'root' => ['view-payment', 'create-payment', 'edit-payment', 'view-payment-method', 'create-payment-method', 'edit-payment-method'],
            'admin' => ['view-payment', 'create-payment', 'edit-payment', 'view-payment-method', 'create-payment-method', 'edit-payment-method'],
            'receptionist' => ['view-payment', 'create-payment'],
            'doctor' => ['view-payment']
        ];

        foreach ($roles as $roleName => $permissionNames) {
            $roleId = DB::table('roles')->where('name', $roleName)->value('id');
            
            if ($roleId) {
                foreach ($permissionNames as $permissionName) {
                    $permissionId = DB::table('permissions')
                        ->where('name', $permissionName)
                        ->value('id');

                    if ($permissionId) {
                        // Verificar si la relación ya existe
                        $exists = DB::table('permission_role')
                            ->where('permission_id', $permissionId)
                            ->where('role_id', $roleId)
                            ->exists();

                        if (!$exists) {
                            DB::table('permission_role')->insert([
                                'permission_id' => $permissionId,
                                'role_id' => $roleId
                            ]);
                        }
                    }
                }
            }
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        // Obtener IDs de los permisos
        $permissionIds = DB::table('permissions')
            ->whereIn('name', [
                'view-payment',
                'create-payment',
                'edit-payment',
                'view-payment-method',
                'create-payment-method',
                'edit-payment-method'
            ])
            ->pluck('id');

        // Eliminar las relaciones de permisos con roles
        DB::table('permission_role')
            ->whereIn('permission_id', $permissionIds)
            ->delete();

        // Eliminar los permisos
        DB::table('permissions')
            ->whereIn('id', $permissionIds)
            ->delete();
    }
} 