<?php

namespace Database\Seeders;

use App\Models\Expense;
use App\Models\ExpenseCategory;
use App\Models\Material;
use App\Models\Purchase;
use App\Models\Supplier;
use App\Models\Unit;
use Carbon\Carbon;
use Illuminate\Database\Seeder;

class PurchaseExpenseSeeder extends Seeder
{
    public function run(): void
    {
        $this->command->info('🚀 Memulai seeding Purchase & Expense (1 Jan - 9 Feb 2026)...');
        
        // Create units first
        $this->createUnits();
        
        // Create expense categories
        $this->createExpenseCategories();
        
        // Create suppliers
        $this->createSuppliers();
        
        // Update materials with stock
        $this->updateMaterialStock();
        
        // Create purchases
        $this->createPurchases();
        
        // Create expenses
        $this->createExpenses();
        
        $this->command->info('✅ Seeding Purchase & Expense selesai!');
    }

    private function createUnits(): void
    {
        $units = [
            ['name' => 'm²', 'symbol' => 'm2'],
            ['name' => 'pcs', 'symbol' => 'pcs'],
            ['name' => 'lembar', 'symbol' => 'lbr'],
            ['name' => 'meter', 'symbol' => 'm'],
            ['name' => 'roll', 'symbol' => 'roll'],
            ['name' => 'pak', 'symbol' => 'pak'],
        ];

        foreach ($units as $unit) {
            Unit::firstOrCreate(['symbol' => $unit['symbol']], $unit);
        }
        
        $this->command->info('  📏 Units seeded: ' . count($units));
    }

    private function createExpenseCategories(): void
    {
        $categories = [
            ['name' => 'Listrik', 'description' => 'Tagihan listrik bulanan'],
            ['name' => 'Token Listrik', 'description' => 'Isi ulang token listrik'],
            ['name' => 'PDAM/Air', 'description' => 'Tagihan air bulanan'],
            ['name' => 'Internet', 'description' => 'Tagihan internet/wifi'],
            ['name' => 'Kasbon Karyawan', 'description' => 'Pinjaman karyawan'],
            ['name' => 'Makan Karyawan', 'description' => 'Makan siang karyawan'],
            ['name' => 'Bensin/Transport', 'description' => 'Biaya transportasi dan bensin'],
            ['name' => 'Peralatan Kantor', 'description' => 'ATK dan peralatan kecil'],
            ['name' => 'Maintenance Mesin', 'description' => 'Perawatan mesin cetak'],
            ['name' => 'Sewa Tempat', 'description' => 'Biaya sewa bulanan'],
            ['name' => 'Paket/Pengiriman', 'description' => 'Ongkir dan COD'],
            ['name' => 'Ambil Modal', 'description' => 'Penarikan modal pemilik'],
            ['name' => 'Lain-lain', 'description' => 'Pengeluaran lainnya'],
        ];

        foreach ($categories as $data) {
            ExpenseCategory::firstOrCreate(['name' => $data['name']], $data);
        }
        
        $this->command->info('  💸 Expense categories seeded: ' . count($categories));
    }

    private function createSuppliers(): void
    {
        $suppliers = [
            [
                'name' => 'CV Media Printing Supply',
                'phone' => '021-5556677',
                'address' => 'Jl. Mangga Dua Raya No. 45, Jakarta Utara',
                'notes' => 'Supplier bahan banner dan sticker',
                'is_active' => true,
            ],
            [
                'name' => 'PT Kertas Nusantara',
                'phone' => '031-8889900',
                'address' => 'Jl. Rungkut Industri No. 12, Surabaya',
                'notes' => 'Supplier kertas art paper dan HVS',
                'is_active' => true,
            ],
            [
                'name' => 'UD Berkah Jaya Material',
                'phone' => '0812-3456-7890',
                'address' => 'Jl. Veteran No. 88, Semarang',
                'notes' => 'Supplier canvas dan wallpaper',
                'is_active' => true,
            ],
            [
                'name' => 'Toko Bintang Advertising',
                'phone' => '0857-1234-5678',
                'address' => 'Jl. Pasar Baru No. 23, Bandung',
                'notes' => 'Supplier X-Banner, Roll Up, tiang display',
                'is_active' => true,
            ],
            [
                'name' => 'PT Vinil Indonesia',
                'phone' => '021-4445566',
                'address' => 'Kawasan Industri Pulogadung, Jakarta Timur',
                'notes' => 'Importir sticker vinyl dan ritrama',
                'is_active' => true,
            ],
        ];

        foreach ($suppliers as $data) {
            Supplier::firstOrCreate(['name' => $data['name']], $data);
        }
        
        $this->command->info('  🏪 Suppliers seeded: ' . count($suppliers));
    }

    private function updateMaterialStock(): void
    {
        $materials = Material::all();
        foreach ($materials as $material) {
            $material->update([
                'stock' => rand(50, 200),
                'min_stock' => rand(10, 30),
            ]);
        }
        
        $this->command->info('  📦 Updated stock for ' . $materials->count() . ' materials');
    }

    private function createPurchases(): void
    {
        $materials = Material::all();
        $suppliers = Supplier::all();
        
        if ($suppliers->isEmpty()) {
            $this->command->warn('  ⚠️ No suppliers found, skipping purchases');
            return;
        }
        
        $startDate = Carbon::create(2026, 1, 1);
        $endDate = Carbon::create(2026, 2, 9);
        $totalPurchases = 0;
        
        // Create 2-4 purchases per week
        $currentDate = $startDate->copy();
        while ($currentDate <= $endDate) {
            // Purchase typically on weekdays
            if (!$currentDate->isWeekend() && rand(1, 7) <= 3) { // ~3 purchases per week
                $material = $materials->random();
                $supplier = $suppliers->random();
                
                $qty = rand(5, 50);
                $unitPrice = rand(15, 100) * 1000; // 15k - 100k per unit
                
                Purchase::create([
                    'material_id' => $material->id,
                    'supplier_id' => $supplier->id,
                    'supplier' => $supplier->name,
                    'purchase_date' => $currentDate->copy(),
                    'quantity' => $qty,
                    'unit_price' => $unitPrice,
                    'total_price' => $qty * $unitPrice,
                    'type' => in_array($material->unit, ['m2', 'meter']) ? 'meteran' : 'satuan',
                    'notes' => 'Pembelian stok ' . $material->name,
                    'created_by' => 1,
                    'created_at' => $currentDate,
                    'updated_at' => $currentDate,
                ]);
                
                $totalPurchases++;
            }
            
            $currentDate->addDay();
        }
        
        $this->command->info('  🛒 Purchases seeded: ' . $totalPurchases);
    }

    private function createExpenses(): void
    {
        $categories = ExpenseCategory::all();
        $startDate = Carbon::create(2026, 1, 1);
        $endDate = Carbon::create(2026, 2, 9);
        $totalExpenses = 0;
        
        // Daily recurring expenses
        $dailyCategories = ['Makan Karyawan'];
        $weeklyCategories = ['Bensin/Transport', 'Peralatan Kantor', 'Paket/Pengiriman'];
        $monthlyCategories = ['Listrik', 'PDAM/Air', 'Internet', 'Sewa Tempat'];
        
        $currentDate = $startDate->copy();
        while ($currentDate <= $endDate) {
            // Daily: Makan karyawan (weekdays only)
            if (!$currentDate->isWeekend()) {
                foreach ($dailyCategories as $catName) {
                    $cat = $categories->firstWhere('name', $catName);
                    if ($cat) {
                        Expense::create([
                            'expense_category_id' => $cat->id,
                            'amount' => rand(5, 8) * 10000, // 50k-80k
                            'expense_date' => $currentDate->copy(),
                            'description' => 'Makan siang ' . $currentDate->translatedFormat('l, d M'),
                            'created_by' => 1,
                            'created_at' => $currentDate,
                            'updated_at' => $currentDate,
                        ]);
                        $totalExpenses++;
                    }
                }
            }
            
            // Weekly expenses (Mondays and Fridays)
            if ($currentDate->isMonday() || $currentDate->isFriday()) {
                $weeklyCategory = $weeklyCategories[array_rand($weeklyCategories)];
                $cat = $categories->firstWhere('name', $weeklyCategory);
                if ($cat && rand(0, 1)) {
                    Expense::create([
                        'expense_category_id' => $cat->id,
                        'amount' => rand(3, 20) * 10000, // 30k-200k
                        'expense_date' => $currentDate->copy(),
                        'description' => $weeklyCategory . ' - ' . $currentDate->format('W') . ' minggu ke-' . $currentDate->weekOfMonth,
                        'created_by' => 1,
                        'created_at' => $currentDate,
                        'updated_at' => $currentDate,
                    ]);
                    $totalExpenses++;
                }
            }
            
            // Monthly expenses (around 1st-5th of month)
            if ($currentDate->day <= 5) {
                foreach ($monthlyCategories as $catName) {
                    $cat = $categories->firstWhere('name', $catName);
                    if ($cat && rand(1, 5) == 1) { // Spread over first 5 days
                        $amounts = match($catName) {
                            'Listrik' => rand(80, 150) * 10000, // 800k-1.5jt
                            'PDAM/Air' => rand(15, 35) * 10000, // 150k-350k
                            'Internet' => rand(30, 50) * 10000, // 300k-500k
                            'Sewa Tempat' => rand(300, 500) * 10000, // 3jt-5jt
                            default => rand(10, 50) * 10000,
                        };
                        
                        Expense::create([
                            'expense_category_id' => $cat->id,
                            'amount' => $amounts,
                            'expense_date' => $currentDate->copy(),
                            'description' => 'Tagihan ' . $catName . ' bulan ' . $currentDate->translatedFormat('F Y'),
                            'created_by' => 1,
                            'created_at' => $currentDate,
                            'updated_at' => $currentDate,
                        ]);
                        $totalExpenses++;
                    }
                }
            }
            
            // Random occasional expenses
            if (rand(1, 10) == 1) {
                $occasionalCategories = ['Kasbon Karyawan', 'Maintenance Mesin', 'Ambil Modal', 'Token Listrik', 'Lain-lain'];
                $catName = $occasionalCategories[array_rand($occasionalCategories)];
                $cat = $categories->firstWhere('name', $catName);
                if ($cat) {
                    $amounts = match($catName) {
                        'Kasbon Karyawan' => rand(20, 100) * 10000, // 200k-1jt
                        'Maintenance Mesin' => rand(30, 200) * 10000, // 300k-2jt
                        'Ambil Modal' => rand(100, 500) * 10000, // 1jt-5jt
                        'Token Listrik' => rand(20, 50) * 10000, // 200k-500k
                        default => rand(5, 30) * 10000,
                    };
                    
                    Expense::create([
                        'expense_category_id' => $cat->id,
                        'amount' => $amounts,
                        'expense_date' => $currentDate->copy(),
                        'description' => $catName . ' - ' . $currentDate->format('d/m'),
                        'created_by' => 1,
                        'created_at' => $currentDate,
                        'updated_at' => $currentDate,
                    ]);
                    $totalExpenses++;
                }
            }
            
            $currentDate->addDay();
        }
        
        $this->command->info('  💸 Expenses seeded: ' . $totalExpenses);
    }
}
