<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use App\Models\User;
use Spatie\Permission\Models\Role;
use Database\Seeders\ConEmpresaSeeder;
use Database\Seeders\MaeParametrosSeeder;
use Database\Seeders\ConUsuariosSeeder;

class DatabaseSeeder extends Seeder
{
    public function run(): void
    {

        DB::statement('SET FOREIGN_KEY_CHECKS=0;');

        DB::table('role_has_permissions')->truncate();
        DB::table('model_has_permissions')->truncate();
        DB::table('model_has_roles')->truncate();
        DB::table('permissions')->truncate();
        DB::table('roles')->truncate();
        DB::table('con_usuarios')->truncate();
        DB::table('con_empresa')->truncate();
        DB::table('mae_parametros')->truncate();

        DB::statement('SET FOREIGN_KEY_CHECKS=1;');

        $this->call([
            ConEmpresaSeeder::class,
            MaeParametrosSeeder::class,
            ConUsuariosSeeder::class,
        ]);

        // Roles
        $roles = ['Supervisor', 'Operador', 'Administrador', 'Gerencia'];

        foreach ($roles as $rol) {
            DB::table('roles')->insert([
                'name' => $rol,
                'guard_name' => 'web',
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }

        // Permisos jerárquicos
        $permisosJerarquia = [
            'Links de Utilidad' => ['ChatGPT', 'GEMINI', 'DeepSeek', 'Grok', 'Qwen', 'NotebookLM', 'Claude'],
            'Configuracion' => ['Empresas', 'Usuarios', 'Roles y Permisos', 'Cambio de Contraseña'],
            'Flujo de trabajo' => ['Procesar archivos', 'Deletear coleccion'],
        ];

        // Permisos simples sin jerarquía
        $permisosSimples = ['Panel de Control', 'Parametros', 'Estadisticas', 'Soporte on Line'];

        // Insertar padres con hijos
        $i = 1;
        foreach ($permisosJerarquia as $padre => $hijos) {
            $parentId = DB::table('permissions')->insertGetId([
                'name' => $padre,
                'guard_name' => 'web',
                'is_parent' => true,
                'parent' => null,
                'route' => null,
                'order' => $i,
                'is_executable' => false,
                'created_at' => now(),
                'updated_at' => now(),
            ]);

            foreach ($hijos as $j => $hijo) {
                DB::table('permissions')->insert([
                    'name' => $hijo,
                    'guard_name' => 'web',
                    'is_parent' => false,
                    'parent' => $parentId,
                    'route' => '/' . Str::slug($hijo),
                    'order' => $j + 1,
                    'is_executable' => true,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
            }

            $i++;
        }

        // Insertar permisos simples
        foreach ($permisosSimples as $permiso) {
            DB::table('permissions')->insert([
                'name' => $permiso,
                'guard_name' => 'web',
                'is_parent' => false,
                'parent' => null,
                'route' => '/' . Str::slug($permiso),
                'is_executable' => true,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }

        // Usuarios [Administrador, Supervisor, Operador]
        $administradorUser = DB::table("con_usuarios")->where("id", 1)->first();
        $supervisorUser = DB::table("con_usuarios")->where("id", 2)->first();
        $operadorUser = DB::table("con_usuarios")->where("id", 3)->first();

        $administradorRole = DB::table('roles')->where('name', 'Administrador')->first();
        $supervisorRole = DB::table('roles')->where('name', 'Supervisor')->first();
        $operadorRole = DB::table('roles')->where('name', 'Operador')->first();

        if ($administradorUser && $administradorRole) {
            DB::table('model_has_roles')->insert([
                'role_id' => $administradorRole->id,
                'model_type' => User::class,
                'model_id' => $administradorUser->id,
            ]);

            $permisosIds = DB::table('permissions')->pluck('id');

            foreach ($permisosIds as $permisoId) {
                DB::table('role_has_permissions')->insert([
                    'role_id' => $administradorRole->id,
                    'permission_id' => $permisoId,
                ]);
            }
        }

        DB::table("permissions")->where('name', 'Panel de Control')->update(['route' => 'panel', 'target' => '_self', 'Order' => 1000, 'icon' => 'layout']);
        DB::table("permissions")->where('name', 'Links de Utilidad')->update(['Order' => 2000, 'icon' => 'external-link']);
        DB::table("permissions")->where('name', 'ChatGPT')->update(['route' => 'https://chatgpt.com/', 'target' => '_blank', 'Order' => 2010]);
        DB::table("permissions")->where('name', 'GEMINI')->update(['route' => 'https://gemini.google.com/app?utm_source=app_launc', 'target' => '_blank', 'Order' => 2020]);
        DB::table("permissions")->where('name', 'DeepSeek')->update(['route' => 'https://chat.deepseek.com/', 'target' => '_blank', 'Order' => 2030]);
        DB::table("permissions")->where('name', 'Grok')->update(['route' => 'https://grok.com/', 'target' => '_blank', 'Order' => 2040]);
        DB::table("permissions")->where('name', 'Qwen')->update(['route' => 'https://chat.qwen.ai/', 'target' => '_blank', 'Order' => 2050]);
        DB::table("permissions")->where('name', 'NotebookLM')->update(['route' => 'https://notebooklm.google.com/?original_referer=ht', 'target' => '_blank', 'Order' => 2060]);
        DB::table("permissions")->where('name', 'Claude')->update(['route' => 'https://claude.ai/chat/1adf3513-8914-45a8-8be9-bcd', 'target' => '_blank', 'Order' => 2070]);
        DB::table("permissions")->where('name', 'Flujo de trabajo')->update(['Order' => 3000, 'icon' => 'trello']);
        DB::table("permissions")->where('name', 'Procesar archivos')->update(['route' => 'flujo.procesar', 'target' => '_self', 'Order' => 3010]);
        DB::table("permissions")->where('name', 'Deletear coleccion')->update(['route' => 'flujo.deletear', 'target' => '_self', 'Order' => 3020]);
        DB::table("permissions")->where('name', 'Parametros')->update(['route' => 'parametros', 'target' => '_self', 'Order' => 4000, 'icon' => 'sliders']);
        DB::table("permissions")->where('name', 'Estadisticas')->update(['route' => 'estadisticas', 'target' => '_self', 'Order' => 5000, 'icon' => 'trending-up']);
        DB::table("permissions")->where('name', 'Configuracion')->update(['Order' => 6000, 'icon' => 'settings']);
        DB::table("permissions")->where('name', 'Empresas')->update(['route' => 'configuracion.empresas', 'target' => '_self', 'Order' => 6010]);
        DB::table("permissions")->where('name', 'Usuarios')->update(['route' => 'configuracion.usuarios', 'target' => '_self', 'Order' => 6020]);
        DB::table("permissions")->where('name', 'Roles y Permisos')->update(['route' => 'configuracion.roles', 'target' => '_self', 'Order' => 6030]);
        DB::table("permissions")->where('name', 'Cambio de Contraseña')->update(['route' => 'configuracion.password', 'target' => '_self', 'Order' => 6040]);
        DB::table("permissions")->where('name', 'Soporte on Line')->update(['route' => 'soporte', 'target' => '_self', 'Order' => 7000, 'icon' => 'tool']);
    }
}
