<?php

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

class AddBudgetPermissions extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // Agregar nuevos permisos
        $permissions = [
            [
                'name' => 'view-budget',
                'display_name' => 'View Budget',
                'description' => 'View Budget',
                'created_at' => now(),
                'updated_at' => now(),
            ],
            [
                'name' => 'create-budget',
                'display_name' => 'Create Budget',
                'description' => 'Create Budget',
                'created_at' => now(),
                'updated_at' => now(),
            ],
            [
                'name' => 'edit-budget',
                'display_name' => 'Edit Budget',
                'description' => 'Edit Budget',
                'created_at' => now(),
                'updated_at' => now(),
            ],
            [
                'name' => 'delete-budget',
                'display_name' => 'Delete Budget',
                'description' => 'Delete Budget',
                'created_at' => now(),
                'updated_at' => now(),
            ],
            [
                'name' => 'send-budget',
                'display_name' => 'Send Budget',
                'description' => 'Send Budget by Email',
                'created_at' => now(),
                'updated_at' => now(),
            ],
            [
                'name' => 'approve-budget',
                'display_name' => 'Approve Budget',
                'description' => 'Approve Budget',
                'created_at' => now(),
                'updated_at' => now(),
            ],
            [
                'name' => 'reject-budget',
                'display_name' => 'Reject Budget',
                'description' => 'Reject Budget',
                'created_at' => now(),
                'updated_at' => now(),
            ],
        ];

        // Insertar solo los permisos que no existen
        foreach ($permissions as $permission) {
            $exists = DB::table('permissions')
                ->where('name', $permission['name'])
                ->exists();

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

        // Asignar permisos a roles admin y root
        $adminRole = DB::table('roles')->where('name', 'admin')->first();
        $rootRole = DB::table('roles')->where('name', 'root')->first();

        foreach ($permissions as $permission) {
            $permissionId = DB::table('permissions')
                ->where('name', $permission['name'])
                ->value('id');

            // Asignar a admin si no existe la relación
            if ($adminRole) {
                $existingAdminPermission = DB::table('permission_role')
                    ->where('permission_id', $permissionId)
                    ->where('role_id', $adminRole->id)
                    ->exists();

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

            // Asignar a root si no existe la relación
            if ($rootRole) {
                $existingRootPermission = DB::table('permission_role')
                    ->where('permission_id', $permissionId)
                    ->where('role_id', $rootRole->id)
                    ->exists();

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

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

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

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