<?php
// database/seeders/DatabaseSeeder.php - VERSI FINAL DENGAN FOREIGN KEY CHECKS

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class DatabaseSeeder extends Seeder
{
    public function run(): void
    {
        // 1. NONAKTIFKAN FOREIGN KEY CHECKS
        Schema::disableForeignKeyConstraints();
        // 2. Truncate semua tabel
        $this->truncateAllTables();

        // 3. AKTIFKAN KEMBALI FOREIGN KEY CHECKS
        Schema::enableForeignKeyConstraints();
        // 4. Run seeders dengan urutan yang benar
        $this->callSeeders();

        // 5. Tampilkan summary
        $this->printSummary();
    }

    private function truncateAllTables(): void
    {
        $this->command->info('Truncating all tables...');

        // DAFTAR SEMUA TABEL DI DATABASE KAMU
        $allTables = [
            'cart_items',
            'carts',
            'order_items',
            'payments',
            'reviews',
            'job_applications',
            'orders',
            'menus',
            'promos',
            'job_postings',
            'categories',
            'users',
            'payment_methods',
            'system_settings',
            'operational_hours',
            'personal_access_tokens',
            'cache',
            'cache_locks',
            'jobs',
            'job_batches',
            'sessions',
            'failed_jobs',
        ];

        foreach ($allTables as $table) {
            if (Schema::hasTable($table)) {
                try {
                    DB::table($table)->truncate();
                    $this->command->info("✓ Truncated: {$table}");
                } catch (\Exception $e) {
                    $this->command->warn("⚠️  Could not truncate {$table}: " . $e->getMessage());
                }
            }
        }

        // Reset auto-increment
        $this->resetAutoIncrement();
    }

    private function resetAutoIncrement(): void
    {
        $this->command->info('Resetting auto-increment...');

        $tables = [
            'users',
            'categories',
            'menus',
            'promos',
            'orders',
            'order_items',
            'payment_methods',
            'payments',
            'reviews',
            'job_postings',
            'job_applications',
            'system_settings',
            'operational_hours',
            'carts',
            'cart_items',
        ];

        foreach ($tables as $table) {
            if (Schema::hasTable($table)) {
                try {
                    DB::statement("ALTER TABLE {$table} AUTO_INCREMENT = 1");
                    $this->command->info("✓ Reset auto-increment: {$table}");
                } catch (\Exception $e) {
                    // Ignore errors for tables without auto-increment
                }
            }
        }
    }

    private function callSeeders(): void
    {
        $this->command->info("\nStarting seeders...");

        $seeders = [
            SystemSettingsSeeder::class,
            PaymentMethodsSeeder::class,
            OperationalHoursSeeder::class,
            UsersSeeder::class,
            CategoriesSeeder::class,
            MenusSeeder::class,
            PromosSeeder::class,
            OrdersSeeder::class,
            ReviewsSeeder::class,
            JobPostingsSeeder::class,
            JobApplicationsSeeder::class,
        ];

        foreach ($seeders as $seeder) {
            $this->command->info("\nRunning: " . class_basename($seeder));
            $this->call($seeder);
        }
    }

    private function printSummary(): void
    {
        $this->command->info("\n" . str_repeat('=', 60));
        $this->command->info('✅ DATABASE SEEDING COMPLETED SUCCESSFULLY!');
        $this->command->info(str_repeat('=', 60));

        $tables = [
            'users' => ['icon' => '👥', 'name' => 'Users'],
            'categories' => ['icon' => '📁', 'name' => 'Categories'],
            'menus' => ['icon' => '🍽️', 'name' => 'Menus'],
            'orders' => ['icon' => '📦', 'name' => 'Orders'],
            'order_items' => ['icon' => '📝', 'name' => 'Order Items'],
            'payments' => ['icon' => '💳', 'name' => 'Payments'],
            'promos' => ['icon' => '🎁', 'name' => 'Promos'],
            'reviews' => ['icon' => '⭐', 'name' => 'Reviews'],
            'job_postings' => ['icon' => '💼', 'name' => 'Job Postings'],
            'job_applications' => ['icon' => '📄', 'name' => 'Job Applications'],
        ];

        foreach ($tables as $table => $info) {
            if (Schema::hasTable($table)) {
                $count = DB::table($table)->count();
                $this->command->info("{$info['icon']} {$info['name']}: {$count}");
            }
        }

        // User breakdown
        $adminCount = DB::table('users')->where('role', 'admin')->count();
        $employeeCount = DB::table('users')->where('role', 'employee')->count();
        $customerCount = DB::table('users')->where('role', 'customer')->count();

        $this->command->info(str_repeat('-', 60));
        $this->command->info("👑 Admins: {$adminCount}");
        $this->command->info("👔 Employees: {$employeeCount}");
        $this->command->info("👥 Customers: {$customerCount}");

        $this->command->info(str_repeat('=', 60));
        $this->command->info('🔐 LOGIN CREDENTIALS FOR TESTING:');
        $this->command->info('   Admin:     admin@chingubite.com / admin123');
        $this->command->info('   Employee:  manager@chingubite.com / employee123');
        $this->command->info('   Customer:  customer@chingubite.com / customer123');
        $this->command->info(str_repeat('=', 60) . "\n");
    }
}
