<?php

namespace Database\Seeders;

use App\Models\User;
use App\Models\Material;
use App\Models\MaterialCategory;
use App\Models\Product;
use App\Models\Setting;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     * 
     * Data period: 1 January 2026 - 9 February 2026
     */
    public function run(): void
    {
        $this->command->info('');
        $this->command->info('╔════════════════════════════════════════════════════════════╗');
        $this->command->info('║       POSGRAF - Database Seeder                            ║');
        $this->command->info('║       Period: 1 January 2026 - 9 February 2026             ║');
        $this->command->info('╚════════════════════════════════════════════════════════════╝');
        $this->command->info('');

        // Create users for each role
        $this->createUsers();

        // Create sample materials
        $this->createMaterials();

        // Create sample products
        $this->createProducts();

        // Create default settings
        $this->createSettings();

        // Initialize RBAC
        $this->call(RolePermissionSeeder::class);

        // Seed payment accounts (bank & e-wallet)
        $this->call(PaymentAccountSeeder::class);

        // Seed employees and salaries
        $this->call(EmployeeSalarySeeder::class);

        // Seed purchases, expenses, suppliers, categories
        $this->call(PurchaseExpenseSeeder::class);

        // Seed finance data (cash modal, deposits, mutations)
        $this->call(FinanceSeeder::class);

        // Seed orders with realistic data
        $this->call(OrderDataSeeder::class);

        $this->command->info('');
        $this->command->info('╔════════════════════════════════════════════════════════════╗');
        $this->command->info('║       ✅ Database seeding completed successfully!          ║');
        $this->command->info('╚════════════════════════════════════════════════════════════╝');
        $this->command->info('');
    }

    private function createUsers(): void
    {
        $this->command->info('👤 Creating users...');
        
        // Developer (Super Admin)
        User::firstOrCreate(
            ['email' => 'developer@posgraf.com'],
            [
                'name' => 'Developer Admin',
                'password' => Hash::make('password'),
                'role' => User::ROLE_DEVELOPER,
                'is_active' => true,
            ]
        );

        // Owner
        User::firstOrCreate(
            ['email' => 'owner@posgraf.com'],
            [
                'name' => 'Haji Supriadi',
                'password' => Hash::make('password'),
                'role' => User::ROLE_OWNER,
                'is_active' => true,
            ]
        );

        // SPV (Supervisor)
        User::firstOrCreate(
            ['email' => 'spv@posgraf.com'],
            [
                'name' => 'Ahmad Supervisor',
                'password' => Hash::make('password'),
                'role' => User::ROLE_SPV,
                'is_active' => true,
            ]
        );

        // Designer 1
        User::firstOrCreate(
            ['email' => 'designer@posgraf.com'],
            [
                'name' => 'Rina Marlina',
                'password' => Hash::make('password'),
                'role' => User::ROLE_DESIGNER,
                'is_active' => true,
            ]
        );

        // Designer 2
        User::firstOrCreate(
            ['email' => 'designer2@posgraf.com'],
            [
                'name' => 'Putri Andini',
                'password' => Hash::make('password'),
                'role' => User::ROLE_DESIGNER,
                'is_active' => true,
            ]
        );

        // Kasir
        User::firstOrCreate(
            ['email' => 'kasir@posgraf.com'],
            [
                'name' => 'Dewi Lestari',
                'password' => Hash::make('password'),
                'role' => User::ROLE_KASIR,
                'is_active' => true,
            ]
        );

        // Operator 1
        User::firstOrCreate(
            ['email' => 'operator@posgraf.com'],
            [
                'name' => 'Budi Santoso',
                'password' => Hash::make('password'),
                'role' => User::ROLE_OPERATOR,
                'is_active' => true,
            ]
        );

        // Operator 2
        User::firstOrCreate(
            ['email' => 'operator2@posgraf.com'],
            [
                'name' => 'Agus Setiawan',
                'password' => Hash::make('password'),
                'role' => User::ROLE_OPERATOR,
                'is_active' => true,
            ]
        );

        $this->command->info('  ✅ Users created: 8 accounts');
    }

    private function createMaterials(): void
    {
        $this->command->info('🎨 Creating materials...');
        
        // First, create material categories
        $categoryNames = ['Banner', 'Sticker', 'Display', 'Kertas', 'Canvas', 'Wallpaper', 'Lainnya'];
        $categoryDescriptions = [
            'Banner' => 'Bahan banner dan spanduk',
            'Sticker' => 'Berbagai jenis sticker',
            'Display' => 'X-Banner, Roll Up, dll',
            'Kertas' => 'Art paper, HVS, karton',
            'Canvas' => 'Canvas printing',
            'Wallpaper' => 'Wallpaper custom',
            'Lainnya' => 'Material lainnya',
        ];
        
        $categories = [];
        foreach ($categoryNames as $catName) {
            $cat = MaterialCategory::firstOrCreate(
                ['name' => $catName],
                [
                    'description' => $categoryDescriptions[$catName] ?? $catName,
                    'is_active' => true,
                ]
            );
            $categories[$catName] = $cat->id;
        }
        
        $materials = [
            // Banner & Spanduk
            ['name' => 'Flexy China 280gr', 'category' => 'Banner', 'base_price' => 25000, 'unit' => 'm2'],
            ['name' => 'Flexy Korea 340gr', 'category' => 'Banner', 'base_price' => 35000, 'unit' => 'm2'],
            ['name' => 'Flexy Jerman 440gr', 'category' => 'Banner', 'base_price' => 45000, 'unit' => 'm2'],
            ['name' => 'Albatros', 'category' => 'Banner', 'base_price' => 55000, 'unit' => 'm2'],
            ['name' => 'Flexy Luster', 'category' => 'Banner', 'base_price' => 40000, 'unit' => 'm2'],

            // Sticker
            ['name' => 'Sticker Vinyl', 'category' => 'Sticker', 'base_price' => 50000, 'unit' => 'm2'],
            ['name' => 'Sticker One Way Vision', 'category' => 'Sticker', 'base_price' => 85000, 'unit' => 'm2'],
            ['name' => 'Sticker Ritrama', 'category' => 'Sticker', 'base_price' => 65000, 'unit' => 'm2'],
            ['name' => 'Sticker Transparan', 'category' => 'Sticker', 'base_price' => 70000, 'unit' => 'm2'],
            ['name' => 'Sticker Chromo', 'category' => 'Sticker', 'base_price' => 45000, 'unit' => 'm2'],
            ['name' => 'Sticker HVS', 'category' => 'Sticker', 'base_price' => 35000, 'unit' => 'm2'],

            // X-Banner & Roll Up
            ['name' => 'X-Banner 60x160', 'category' => 'Display', 'base_price' => 75000, 'unit' => 'pcs'],
            ['name' => 'X-Banner 80x180', 'category' => 'Display', 'base_price' => 100000, 'unit' => 'pcs'],
            ['name' => 'Roll Up Banner 85x200', 'category' => 'Display', 'base_price' => 250000, 'unit' => 'pcs'],
            ['name' => 'Mini X-Banner 25x40', 'category' => 'Display', 'base_price' => 35000, 'unit' => 'pcs'],

            // Kertas
            ['name' => 'Art Paper 120gr', 'category' => 'Kertas', 'base_price' => 1500, 'unit' => 'lembar'],
            ['name' => 'Art Paper 150gr', 'category' => 'Kertas', 'base_price' => 2000, 'unit' => 'lembar'],
            ['name' => 'Art Carton 260gr', 'category' => 'Kertas', 'base_price' => 3000, 'unit' => 'lembar'],
            ['name' => 'Art Carton 310gr', 'category' => 'Kertas', 'base_price' => 3500, 'unit' => 'lembar'],
            ['name' => 'HVS 70gr', 'category' => 'Kertas', 'base_price' => 400, 'unit' => 'lembar'],
            ['name' => 'HVS 80gr', 'category' => 'Kertas', 'base_price' => 500, 'unit' => 'lembar'],
            ['name' => 'Ivory 230gr', 'category' => 'Kertas', 'base_price' => 2500, 'unit' => 'lembar'],

            // Canvas & Wallpaper
            ['name' => 'Canvas Premium', 'category' => 'Canvas', 'base_price' => 150000, 'unit' => 'm2'],
            ['name' => 'Canvas Standard', 'category' => 'Canvas', 'base_price' => 100000, 'unit' => 'm2'],
            ['name' => 'Wallpaper Custom', 'category' => 'Wallpaper', 'base_price' => 120000, 'unit' => 'm2'],
            ['name' => 'Wallpaper Sticker', 'category' => 'Wallpaper', 'base_price' => 90000, 'unit' => 'm2'],

            // Lainnya
            ['name' => 'Backlite Film', 'category' => 'Lainnya', 'base_price' => 80000, 'unit' => 'm2'],
            ['name' => 'Kain/Textile', 'category' => 'Lainnya', 'base_price' => 75000, 'unit' => 'm2'],
            ['name' => 'Acrylic 3mm', 'category' => 'Lainnya', 'base_price' => 250000, 'unit' => 'm2'],
            ['name' => 'Acrylic 5mm', 'category' => 'Lainnya', 'base_price' => 350000, 'unit' => 'm2'],
        ];

        foreach ($materials as $material) {
            Material::firstOrCreate(
                ['name' => $material['name']],
                [
                    'category_id' => $categories[$material['category']] ?? null,
                    'base_price' => $material['base_price'],
                    'unit' => $material['unit'],
                    'is_active' => true,
                ]
            );
        }
        
        $this->command->info('  ✅ Materials created: ' . count($materials) . ' (with ' . count($categories) . ' categories)');
    }

    private function createProducts(): void
    {
        $this->command->info('📦 Creating products...');
        
        $products = [
            [
                'name' => 'Cetak Banner',
                'code' => 'BANNER',
                'description' => 'Cetak banner berbagai ukuran dengan bahan flexy berkualitas',
                'material_categories' => ['Banner'],
            ],
            [
                'name' => 'Cetak Spanduk',
                'code' => 'SPANDUK',
                'description' => 'Cetak spanduk untuk promosi dan acara',
                'material_categories' => ['Banner'],
            ],
            [
                'name' => 'Cetak Sticker',
                'code' => 'STICKER',
                'description' => 'Cetak sticker vinyl, ritrama, dan one way vision',
                'material_categories' => ['Sticker'],
            ],
            [
                'name' => 'X-Banner',
                'code' => 'XBANNER',
                'description' => 'Paket X-Banner lengkap dengan tiang',
                'material_categories' => ['Display'],
            ],
            [
                'name' => 'Roll Up Banner',
                'code' => 'ROLLUP',
                'description' => 'Roll up banner premium untuk pameran dan event',
                'material_categories' => ['Display'],
            ],
            [
                'name' => 'Cetak Brosur',
                'code' => 'BROSUR',
                'description' => 'Cetak brosur dengan berbagai jenis kertas',
                'material_categories' => ['Kertas'],
            ],
            [
                'name' => 'Cetak Poster',
                'code' => 'POSTER',
                'description' => 'Cetak poster ukuran A3, A2, A1, A0',
                'material_categories' => ['Kertas'],
            ],
            [
                'name' => 'Cetak Flyer',
                'code' => 'FLYER',
                'description' => 'Cetak flyer promosi berbagai ukuran',
                'material_categories' => ['Kertas'],
            ],
            [
                'name' => 'Cetak Kartu Nama',
                'code' => 'KARTUNAM',
                'description' => 'Cetak kartu nama profesional',
                'material_categories' => ['Kertas'],
            ],
            [
                'name' => 'Cetak Canvas',
                'code' => 'CANVAS',
                'description' => 'Cetak foto atau artwork di canvas premium',
                'material_categories' => ['Canvas'],
            ],
            [
                'name' => 'Wallpaper Custom',
                'code' => 'WALLPAPER',
                'description' => 'Wallpaper custom dengan desain sendiri',
                'material_categories' => ['Wallpaper'],
            ],
            [
                'name' => 'Neon Box',
                'code' => 'NEONBOX',
                'description' => 'Pembuatan neon box dengan backlight',
                'material_categories' => ['Lainnya'],
            ],
            [
                'name' => 'Letter Sign',
                'code' => 'LETTERSIGN',
                'description' => 'Huruf timbul acrylic untuk signage',
                'material_categories' => ['Lainnya'],
            ],
            [
                'name' => 'Backdrop Event',
                'code' => 'BACKDROP',
                'description' => 'Backdrop untuk event dan photobooth',
                'material_categories' => ['Banner', 'Lainnya'],
            ],
        ];

        foreach ($products as $productData) {
            $product = Product::firstOrCreate(
                ['code' => $productData['code']],
                [
                    'name' => $productData['name'],
                    'description' => $productData['description'],
                    'is_active' => true,
                ]
            );

            // Attach materials based on category
            if (!empty($productData['material_categories'])) {
                $materialIds = Material::whereHas('category', function ($query) use ($productData) {
                    $query->whereIn('name', $productData['material_categories']);
                })->pluck('id')->toArray();
                
                $product->materials()->syncWithoutDetaching($materialIds);
            }
        }
        
        $this->command->info('  ✅ Products created: ' . count($products));
    }

    private function createSettings(): void
    {
        $this->command->info('⚙️ Creating settings...');
        
        $settings = [
            ['key' => 'shop_name', 'value' => 'POSGRAF Digital Printing', 'group' => 'shop'],
            ['key' => 'shop_address', 'value' => 'Jl. Percetakan No. 123, Kelurahan Sukamaju, Kec. Maju Jaya, Kota Jakarta Selatan 12345', 'group' => 'shop'],
            ['key' => 'shop_phone', 'value' => '021-5556677', 'group' => 'shop'],
            ['key' => 'shop_whatsapp', 'value' => '0812-3456-7890', 'group' => 'shop'],
            ['key' => 'shop_email', 'value' => 'order@posgraf.com', 'group' => 'shop'],
            ['key' => 'shop_footer', 'value' => 'Terima kasih atas kepercayaan Anda! Barang yang sudah dipesan tidak dapat dikembalikan.', 'group' => 'shop'],
            ['key' => 'shop_instagram', 'value' => '@posgraf_printing', 'group' => 'social'],
        ];

        foreach ($settings as $setting) {
            Setting::firstOrCreate(
                ['key' => $setting['key']],
                [
                    'value' => $setting['value'],
                    'group' => $setting['group'],
                ]
            );
        }
        
        $this->command->info('  ✅ Settings created: ' . count($settings));
    }
}
