<?php

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

class UpdatePermissionsAndRoles extends Migration
{
    public function up()
    {
        // Limpiar tablas existentes
        DB::table('permission_role')->truncate();
        DB::table('role_user')->truncate();
        DB::table('permission_user')->truncate();
        DB::table('roles')->truncate();
        DB::table('permissions')->truncate();

        // Crear roles
        $roles = [
            [
                'id' => 1,
                'name' => 'root',
                'display_name' => 'Super Administrador',
                'description' => 'Usuario con acceso total al sistema',
                'created_at' => now(),
                'updated_at' => now()
            ],
            [
                'id' => 2,
                'name' => 'admin',
                'display_name' => 'Administrador',
                'description' => 'Administrador del sistema',
                'created_at' => now(),
                'updated_at' => now()
            ],
            [
                'id' => 3,
                'name' => 'receptionist',
                'display_name' => 'Recepcionista',
                'description' => 'Recepcionista del sistema',
                'created_at' => now(),
                'updated_at' => now()
            ],
            [
                'id' => 4,
                'name' => 'doctor',
                'display_name' => 'Doctor',
                'description' => 'Doctor del sistema',
                'created_at' => now(),
                'updated_at' => now()
            ]
        ];

        DB::table('roles')->insert($roles);

        // Crear permisos basados en las rutas
        $permissions = [
            // Dashboard y configuración
            ['name' => 'view-dashboard', 'display_name' => 'Ver Dashboard', 'description' => 'Acceso al dashboard'],
            ['name' => 'view-config', 'display_name' => 'Ver Configuración', 'description' => 'Ver configuración del sistema'],
            ['name' => 'edit-config', 'display_name' => 'Editar Configuración', 'description' => 'Editar configuración del sistema'],
            
            // Citas
            ['name' => 'view-appointment', 'display_name' => 'Ver Citas', 'description' => 'Ver listado de citas'],
            ['name' => 'create-appointment', 'display_name' => 'Crear Citas', 'description' => 'Crear nuevas citas'],
            ['name' => 'edit-appointment', 'display_name' => 'Editar Citas', 'description' => 'Modificar citas existentes'],
            ['name' => 'delete-appointment', 'display_name' => 'Eliminar Citas', 'description' => 'Eliminar citas'],
            ['name' => 'close-appointment', 'display_name' => 'Cerrar Citas', 'description' => 'Marcar citas como completadas'],
            
            // Pacientes
            ['name' => 'view-patient', 'display_name' => 'Ver Pacientes', 'description' => 'Ver listado de pacientes'],
            ['name' => 'create-patient', 'display_name' => 'Crear Pacientes', 'description' => 'Registrar nuevos pacientes'],
            ['name' => 'edit-patient', 'display_name' => 'Editar Pacientes', 'description' => 'Modificar datos de pacientes'],
            ['name' => 'delete-patient', 'display_name' => 'Eliminar Pacientes', 'description' => 'Eliminar pacientes'],
            
            // Historias médicas
            ['name' => 'view-history', 'display_name' => 'Ver Historias', 'description' => 'Ver historias médicas'],
            ['name' => 'create-history', 'display_name' => 'Crear Historias', 'description' => 'Crear nuevas historias'],
            ['name' => 'edit-history', 'display_name' => 'Editar Historias', 'description' => 'Modificar historias'],
            ['name' => 'delete-history', 'display_name' => 'Eliminar Historias', 'description' => 'Eliminar historias'],
            ['name' => 'download-history', 'display_name' => 'Descargar Historias', 'description' => 'Descargar historias'],
            ['name' => 'configure-history', 'display_name' => 'Configurar Historias', 'description' => 'Configurar plantillas de historias'],
            
            // Control de historias
            ['name' => 'view-control-history', 'display_name' => 'Ver Control de Historia', 'description' => 'Ver controles de historia'],
            ['name' => 'create-control-history', 'display_name' => 'Crear Control de Historia', 'description' => 'Crear controles de historia'],
            ['name' => 'edit-control-history', 'display_name' => 'Editar Control de Historia', 'description' => 'Modificar controles de historia'],
            
            // Reportes médicos
            ['name' => 'view-medical-report', 'display_name' => 'Ver Reportes Médicos', 'description' => 'Ver reportes médicos'],
            ['name' => 'create-medical-report', 'display_name' => 'Crear Reportes Médicos', 'description' => 'Crear reportes médicos'],
            ['name' => 'edit-medical-report', 'display_name' => 'Editar Reportes Médicos', 'description' => 'Modificar reportes médicos'],
            ['name' => 'download-medical-report', 'display_name' => 'Descargar Reportes Médicos', 'description' => 'Descargar reportes médicos'],
            
            // Recetas médicas
            ['name' => 'view-medical-recipe', 'display_name' => 'Ver Recetas', 'description' => 'Ver recetas médicas'],
            ['name' => 'create-medical-recipe', 'display_name' => 'Crear Recetas', 'description' => 'Crear recetas médicas'],
            ['name' => 'edit-medical-recipe', 'display_name' => 'Editar Recetas', 'description' => 'Modificar recetas médicas'],
            ['name' => 'download-medical-recipe', 'display_name' => 'Descargar Recetas', 'description' => 'Descargar recetas médicas'],
            
            // Representantes
            ['name' => 'view-representative', 'display_name' => 'Ver Representantes', 'description' => 'Ver representantes'],
            ['name' => 'create-representative', 'display_name' => 'Crear Representantes', 'description' => 'Crear representantes'],
            ['name' => 'edit-representative', 'display_name' => 'Editar Representantes', 'description' => 'Modificar representantes'],
            
            // Usuarios
            ['name' => 'view-user', 'display_name' => 'Ver Usuarios', 'description' => 'Ver usuarios del sistema'],
            ['name' => 'create-user', 'display_name' => 'Crear Usuarios', 'description' => 'Crear usuarios'],
            ['name' => 'edit-user', 'display_name' => 'Editar Usuarios', 'description' => 'Modificar usuarios'],
            ['name' => 'delete-user', 'display_name' => 'Eliminar Usuarios', 'description' => 'Eliminar usuarios'],
            
            // Áreas/Especialidades
            ['name' => 'view-area', 'display_name' => 'Ver Áreas', 'description' => 'Ver áreas/especialidades'],
            ['name' => 'create-area', 'display_name' => 'Crear Áreas', 'description' => 'Crear áreas/especialidades'],
            ['name' => 'edit-area', 'display_name' => 'Editar Áreas', 'description' => 'Modificar áreas/especialidades'],
            
            // Pagos y finanzas
            ['name' => 'view-payment', 'display_name' => 'Ver Pagos', 'description' => 'Ver pagos'],
            ['name' => 'create-payment', 'display_name' => 'Crear Pagos', 'description' => 'Registrar pagos'],
            ['name' => 'edit-payment', 'display_name' => 'Editar Pagos', 'description' => 'Modificar pagos'],
            
            // Presupuestos
            ['name' => 'view-budget', 'display_name' => 'Ver Presupuestos', 'description' => 'Ver presupuestos'],
            ['name' => 'create-budget', 'display_name' => 'Crear Presupuestos', 'description' => 'Crear presupuestos'],
            ['name' => 'edit-budget', 'display_name' => 'Editar Presupuestos', 'description' => 'Modificar presupuestos'],
            ['name' => 'delete-budget', 'display_name' => 'Eliminar Presupuestos', 'description' => 'Eliminar presupuestos'],
            ['name' => 'send-budget', 'display_name' => 'Enviar Presupuestos', 'description' => 'Enviar presupuestos'],
            ['name' => 'approve-budget', 'display_name' => 'Aprobar Presupuestos', 'description' => 'Aprobar presupuestos'],
            ['name' => 'reject-budget', 'display_name' => 'Rechazar Presupuestos', 'description' => 'Rechazar presupuestos'],
            
            // Servicios médicos
            ['name' => 'view-medical-service', 'display_name' => 'Ver Servicios Médicos', 'description' => 'Ver servicios médicos'],
            ['name' => 'create-medical-service', 'display_name' => 'Crear Servicios Médicos', 'description' => 'Crear servicios médicos'],
            ['name' => 'edit-medical-service', 'display_name' => 'Editar Servicios Médicos', 'description' => 'Modificar servicios médicos'],
            ['name' => 'delete-medical-service', 'display_name' => 'Eliminar Servicios Médicos', 'description' => 'Eliminar servicios médicos'],
            
            // Utilidades
            ['name' => 'view-utilities', 'display_name' => 'Ver Utilidades', 'description' => 'Acceso a utilidades del sistema'],
            
            // Auditoría
            ['name' => 'view-audit', 'display_name' => 'Ver Auditoría', 'description' => 'Ver registros de auditoría'],
            ['name' => 'manage-audit', 'display_name' => 'Gestionar Auditoría', 'description' => 'Gestionar registros de auditoría'],
            
            // Email
            ['name' => 'view-email', 'display_name' => 'Ver Emails', 'description' => 'Ver correos electrónicos'],
            ['name' => 'send-email', 'display_name' => 'Enviar Emails', 'description' => 'Enviar correos electrónicos'],
            
            // Permisos para horarios de doctores
            ['name' => 'doctor-schedules-list', 'display_name' => 'Ver horarios', 'description' => 'Ver listado de horarios de doctores'],
            ['name' => 'doctor-schedules-create', 'display_name' => 'Crear horarios', 'description' => 'Crear nuevos horarios de doctores'],
            ['name' => 'doctor-schedules-edit', 'display_name' => 'Editar horarios', 'description' => 'Editar horarios existentes de doctores'],
            ['name' => 'doctor-schedules-delete', 'display_name' => 'Eliminar horarios', 'description' => 'Eliminar horarios de doctores']
        ];

        foreach ($permissions as $permission) {
            $permission['created_at'] = now();
            $permission['updated_at'] = now();
            DB::table('permissions')->insert($permission);
        }

        // Obtener todos los IDs de permisos
        $allPermissionIds = DB::table('permissions')->pluck('id')->toArray();
        
        // Asignar TODOS los permisos a root y admin
        foreach ([1, 2] as $roleId) { // 1 = root, 2 = admin
            foreach ($allPermissionIds as $permissionId) {
                DB::table('permission_role')->insert([
                    'permission_id' => $permissionId,
                    'role_id' => $roleId
                ]);
            }
        }

        // Permisos para recepcionista
        $receptionistPermissions = [
            'view-dashboard',
            'view-appointment', 'create-appointment', 'edit-appointment',
            'view-patient', 'create-patient',
            'view-history', 'download-history',
            'view-medical-report', 'download-medical-report',
            'view-medical-recipe', 'download-medical-recipe',
            'view-representative', 'create-representative',
            'view-user',
            'view-area',
            'view-payment', 'create-payment',
            'view-budget', 'create-budget',
            'view-medical-service',
            'view-utilities',
            'view-email', 'send-email'
        ];

        foreach ($receptionistPermissions as $permissionName) {
            $permissionId = DB::table('permissions')->where('name', $permissionName)->value('id');
            if ($permissionId) {
                DB::table('permission_role')->insert([
                    'permission_id' => $permissionId,
                    'role_id' => 3 // 3 = receptionist
                ]);
            }
        }

        // Permisos para doctor
        $doctorPermissions = [
            'view-dashboard',
            'view-appointment', 'edit-appointment', 'close-appointment',
            'view-patient', 'edit-patient',
            'view-history', 'create-history', 'edit-history', 'download-history',
            'view-control-history', 'create-control-history', 'edit-control-history',
            'view-medical-report', 'create-medical-report', 'edit-medical-report', 'download-medical-report',
            'view-medical-recipe', 'create-medical-recipe', 'edit-medical-recipe', 'download-medical-recipe',
            'view-representative',
            'view-user',
            'view-area',
            'view-payment',
            'view-budget', 'create-budget', 'send-budget',
            'view-medical-service',
            'view-utilities',
            'view-email', 'send-email'
        ];

        foreach ($doctorPermissions as $permissionName) {
            $permissionId = DB::table('permissions')->where('name', $permissionName)->value('id');
            if ($permissionId) {
                DB::table('permission_role')->insert([
                    'permission_id' => $permissionId,
                    'role_id' => 4 // 4 = doctor
                ]);
            }
        }

        // Asignar rol root al usuario root si existe
        $rootUser = DB::table('users')->where('email', 'root@root.com')->first();
        if ($rootUser) {
            DB::table('role_user')->insert([
                'role_id' => 1,
                'user_id' => $rootUser->id,
                'user_type' => 'App\\Models\\User',
                'created_at' => now(),
                'updated_at' => now()
            ]);
        }
    }

    public function down()
    {
        DB::table('permission_role')->truncate();
        DB::table('role_user')->truncate();
        DB::table('permission_user')->truncate();
        DB::table('roles')->truncate();
        DB::table('permissions')->truncate();
    }
} 