<?php

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

return new class extends Migration
{
    public function up(): void
    {
        // Roles table
        Schema::create('roles', function (Blueprint $table) {
            $table->id();
            $table->string('name')->unique();
            $table->string('display_name');
            $table->string('description')->nullable();
            $table->string('type')->default('admin'); // admin, business, user
            $table->boolean('is_system')->default(false);
            $table->timestamps();
        });

        // Permissions table
        Schema::create('permissions', function (Blueprint $table) {
            $table->id();
            $table->string('name')->unique();
            $table->string('display_name');
            $table->string('group')->default('general');
            $table->string('description')->nullable();
            $table->timestamps();
        });

        // Role-Permission pivot
        Schema::create('role_permission', function (Blueprint $table) {
            $table->id();
            $table->foreignId('role_id')->constrained()->onDelete('cascade');
            $table->foreignId('permission_id')->constrained()->onDelete('cascade');
            $table->timestamps();

            $table->unique(['role_id', 'permission_id']);
        });

        // User-Role pivot
        Schema::create('user_role', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->foreignId('role_id')->constrained()->onDelete('cascade');
            $table->foreignId('business_id')->nullable()->constrained()->onDelete('cascade');
            $table->timestamps();

            $table->unique(['user_id', 'role_id', 'business_id']);
        });

        // Insert default roles
        DB::table('roles')->insert([
            // Super Admin
            [
                'name' => 'super_admin',
                'display_name' => 'Super Administrator',
                'description' => 'Full system access with configuration control',
                'type' => 'admin',
                'is_system' => true,
                'created_at' => now(),
                'updated_at' => now(),
            ],
            // Admin
            [
                'name' => 'admin',
                'display_name' => 'Administrator',
                'description' => 'Platform management and moderation',
                'type' => 'admin',
                'is_system' => true,
                'created_at' => now(),
                'updated_at' => now(),
            ],
            // Business Owner
            [
                'name' => 'business_owner',
                'display_name' => 'Business Owner',
                'description' => 'Full business management access',
                'type' => 'business',
                'is_system' => true,
                'created_at' => now(),
                'updated_at' => now(),
            ],
            // Business Manager
            [
                'name' => 'business_manager',
                'display_name' => 'Business Manager',
                'description' => 'Manage venues and offers',
                'type' => 'business',
                'is_system' => true,
                'created_at' => now(),
                'updated_at' => now(),
            ],
            // Venue Staff
            [
                'name' => 'venue_staff',
                'display_name' => 'Venue Staff',
                'description' => 'Scan and redeem offers',
                'type' => 'business',
                'is_system' => true,
                'created_at' => now(),
                'updated_at' => now(),
            ],
            // Regular User
            [
                'name' => 'user',
                'display_name' => 'User',
                'description' => 'Regular app user',
                'type' => 'user',
                'is_system' => true,
                'created_at' => now(),
                'updated_at' => now(),
            ],
        ]);

        // Insert permissions
        $permissions = [
            // User Management
            ['name' => 'users_view', 'display_name' => 'View Users', 'group' => 'user_management'],
            ['name' => 'users_create', 'display_name' => 'Create Users', 'group' => 'user_management'],
            ['name' => 'users_edit', 'display_name' => 'Edit Users', 'group' => 'user_management'],
            ['name' => 'users_delete', 'display_name' => 'Delete Users', 'group' => 'user_management'],
            ['name' => 'users_manage_roles', 'display_name' => 'Manage User Roles', 'group' => 'user_management'],

            // Business Management
            ['name' => 'businesses_view', 'display_name' => 'View Businesses', 'group' => 'business_management'],
            ['name' => 'businesses_verify', 'display_name' => 'Verify Businesses', 'group' => 'business_management'],
            ['name' => 'businesses_edit', 'display_name' => 'Edit Businesses', 'group' => 'business_management'],
            ['name' => 'businesses_delete', 'display_name' => 'Delete Businesses', 'group' => 'business_management'],

            // Venue Management
            ['name' => 'venues_view', 'display_name' => 'View Venues', 'group' => 'venue_management'],
            ['name' => 'venues_create', 'display_name' => 'Create Venues', 'group' => 'venue_management'],
            ['name' => 'venues_edit', 'display_name' => 'Edit Venues', 'group' => 'venue_management'],
            ['name' => 'venues_delete', 'display_name' => 'Delete Venues', 'group' => 'venue_management'],
            ['name' => 'venues_approve', 'display_name' => 'Approve Venues', 'group' => 'venue_management'],

            // Offer Management
            ['name' => 'offers_view', 'display_name' => 'View Offers', 'group' => 'offer_management'],
            ['name' => 'offers_create', 'display_name' => 'Create Offers', 'group' => 'offer_management'],
            ['name' => 'offers_edit', 'display_name' => 'Edit Offers', 'group' => 'offer_management'],
            ['name' => 'offers_delete', 'display_name' => 'Delete Offers', 'group' => 'offer_management'],
            ['name' => 'offers_approve', 'display_name' => 'Approve Offers', 'group' => 'offer_management'],

            // Redemption Management
            ['name' => 'redemptions_view', 'display_name' => 'View Redemptions', 'group' => 'redemption_management'],
            ['name' => 'redemptions_scan', 'display_name' => 'Scan QR Codes', 'group' => 'redemption_management'],
            ['name' => 'redemptions_redeem', 'display_name' => 'Redeem Offers', 'group' => 'redemption_management'],

            // Content Moderation
            ['name' => 'spotlights_view', 'display_name' => 'View Spotlights', 'group' => 'content_moderation'],
            ['name' => 'spotlights_moderate', 'display_name' => 'Moderate Spotlights', 'group' => 'content_moderation'],
            ['name' => 'spotlights_delete', 'display_name' => 'Delete Spotlights', 'group' => 'content_moderation'],

            // Subscription Management
            ['name' => 'subscriptions_view', 'display_name' => 'View Subscriptions', 'group' => 'subscription_management'],
            ['name' => 'subscriptions_manage', 'display_name' => 'Manage Subscriptions', 'group' => 'subscription_management'],
            ['name' => 'subscription_plans_manage', 'display_name' => 'Manage Plans', 'group' => 'subscription_management'],

            // Analytics
            ['name' => 'analytics_view', 'display_name' => 'View Analytics', 'group' => 'analytics'],
            ['name' => 'analytics_export', 'display_name' => 'Export Analytics', 'group' => 'analytics'],

            // System Configuration
            ['name' => 'config_view', 'display_name' => 'View Configuration', 'group' => 'system'],
            ['name' => 'config_edit', 'display_name' => 'Edit Configuration', 'group' => 'system'],
            ['name' => 'audit_logs_view', 'display_name' => 'View Audit Logs', 'group' => 'system'],

            // Team Management
            ['name' => 'team_view', 'display_name' => 'View Team', 'group' => 'team_management'],
            ['name' => 'team_create', 'display_name' => 'Add Team Members', 'group' => 'team_management'],
            ['name' => 'team_edit', 'display_name' => 'Edit Team Members', 'group' => 'team_management'],
            ['name' => 'team_delete', 'display_name' => 'Remove Team Members', 'group' => 'team_management'],

            // GDPR
            ['name' => 'gdpr_view', 'display_name' => 'View GDPR Requests', 'group' => 'gdpr'],
            ['name' => 'gdpr_process', 'display_name' => 'Process GDPR Requests', 'group' => 'gdpr'],
        ];

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

        // Assign all permissions to super_admin
        $superAdminRole = DB::table('roles')->where('name', 'super_admin')->first();
        $allPermissions = DB::table('permissions')->get();

        foreach ($allPermissions as $permission) {
            DB::table('role_permission')->insert([
                'role_id' => $superAdminRole->id,
                'permission_id' => $permission->id,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }

        // Assign permissions to admin role
        $adminRole = DB::table('roles')->where('name', 'admin')->first();
        $adminPermissions = [
            'users_view', 'users_edit',
            'businesses_view', 'businesses_verify', 'businesses_edit',
            'venues_view', 'venues_approve', 'venues_edit',
            'offers_view', 'offers_approve', 'offers_edit',
            'spotlights_view', 'spotlights_moderate', 'spotlights_delete',
            'subscriptions_view', 'subscriptions_manage',
            'analytics_view', 'analytics_export',
            'gdpr_view', 'gdpr_process',
        ];

        foreach ($adminPermissions as $permName) {
            $perm = DB::table('permissions')->where('name', $permName)->first();
            if ($perm) {
                DB::table('role_permission')->insert([
                    'role_id' => $adminRole->id,
                    'permission_id' => $perm->id,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
            }
        }

        // Assign permissions to business_owner
        $businessOwnerRole = DB::table('roles')->where('name', 'business_owner')->first();
        $businessOwnerPermissions = [
            'venues_view', 'venues_create', 'venues_edit', 'venues_delete',
            'offers_view', 'offers_create', 'offers_edit', 'offers_delete',
            'redemptions_view',
            'analytics_view', 'analytics_export',
            'team_view', 'team_create', 'team_edit', 'team_delete',
        ];

        foreach ($businessOwnerPermissions as $permName) {
            $perm = DB::table('permissions')->where('name', $permName)->first();
            if ($perm) {
                DB::table('role_permission')->insert([
                    'role_id' => $businessOwnerRole->id,
                    'permission_id' => $perm->id,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
            }
        }

        // Assign permissions to business_manager
        $businessManagerRole = DB::table('roles')->where('name', 'business_manager')->first();
        $businessManagerPermissions = [
            'venues_view', 'venues_edit',
            'offers_view', 'offers_create', 'offers_edit',
            'redemptions_view',
            'analytics_view',
        ];

        foreach ($businessManagerPermissions as $permName) {
            $perm = DB::table('permissions')->where('name', $permName)->first();
            if ($perm) {
                DB::table('role_permission')->insert([
                    'role_id' => $businessManagerRole->id,
                    'permission_id' => $perm->id,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
            }
        }

        // Assign permissions to venue_staff
        $venueStaffRole = DB::table('roles')->where('name', 'venue_staff')->first();
        $venueStaffPermissions = [
            'redemptions_scan',
            'redemptions_redeem',
        ];

        foreach ($venueStaffPermissions as $permName) {
            $perm = DB::table('permissions')->where('name', $permName)->first();
            if ($perm) {
                DB::table('role_permission')->insert([
                    'role_id' => $venueStaffRole->id,
                    'permission_id' => $perm->id,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
            }
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('user_role');
        Schema::dropIfExists('role_permission');
        Schema::dropIfExists('permissions');
        Schema::dropIfExists('roles');
    }
};
