<?php

declare(strict_types=1);

namespace Database\Seeders;

use App\Models\Outlet;
use App\Models\Ingredient;
use App\Models\OutletIngredient;
use App\Models\OutletProduct;
use App\Models\Product;
use App\Models\Recipe;
use App\Models\Transaction;
use App\Models\TransactionItem;
use App\Models\User;
use App\Models\Supplier;
use App\Models\Table;
use App\Models\Customer;
use App\Models\Courier;
use App\Models\Voucher;
use App\Models\PurchaseOrder;
use App\Models\PurchaseOrderItem;
use App\Models\StockTransaction;
use App\Models\Modifier;
use App\Models\Promo;
use Illuminate\Database\Seeder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

class CafePOSDummySeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // Disable foreign keys check
        \Illuminate\Support\Facades\Schema::disableForeignKeyConstraints();

        // Truncate tables to ensure a clean seed run
        TransactionItem::truncate();
        Transaction::truncate();
        PurchaseOrderItem::truncate();
        PurchaseOrder::truncate();
        StockTransaction::truncate();
        OutletIngredient::truncate();
        OutletProduct::truncate();
        Recipe::truncate();
        Product::truncate();
        Ingredient::truncate();
        Supplier::truncate();
        Table::truncate();
        Customer::truncate();
        Courier::truncate();
        Voucher::truncate();
        Modifier::truncate();
        Promo::truncate();

        \Illuminate\Support\Facades\Schema::enableForeignKeyConstraints();

        // 1. Create Outlets
        $kemang = Outlet::firstOrCreate(
            ['name' => 'CafePOS Kemang'],
            [
                'location' => 'Jalan Kemang Raya No. 4, Jakarta Selatan',
                'description' => 'Sore hangout spot with outdoor canopy.',
            ]
        );

        $senopati = Outlet::firstOrCreate(
            ['name' => 'CafePOS Senopati'],
            [
                'location' => 'Jalan Senopati No. 88, Jakarta Selatan',
                'description' => 'Busy executive business hub outlet.',
            ]
        );

        // 2. Create Users & Waiters
        $admin = User::firstOrCreate(
            ['email' => 'admin@example.com'],
            [
                'name' => 'Admin User',
                'password' => bcrypt('password'),
            ]
        );
        $admin->syncRoles(['Admin']);

        $owner = User::firstOrCreate(
            ['email' => 'owner@example.com'],
            [
                'name' => 'Owner Coffee',
                'password' => bcrypt('password'),
            ]
        );
        $owner->syncRoles(['Owner']);

        $cashier1 = User::firstOrCreate(
            ['email' => 'cashier@example.com'],
            [
                'name' => 'Kasir Kemang',
                'password' => bcrypt('password'),
                'outlet_id' => $kemang->id,
            ]
        );
        $cashier1->syncRoles(['Kasir']);

        $cashier2 = User::firstOrCreate(
            ['email' => 'cashier2@example.com'],
            [
                'name' => 'Kasir Senopati',
                'password' => bcrypt('password'),
                'outlet_id' => $senopati->id,
            ]
        );
        $cashier2->syncRoles(['Kasir']);

        $kitchen1 = User::firstOrCreate(
            ['email' => 'kitchen@example.com'],
            [
                'name' => 'Kitchen Kemang',
                'password' => bcrypt('password'),
                'outlet_id' => $kemang->id,
            ]
        );
        $kitchen1->syncRoles(['Kitchen']);

        // Waiter Users
        $waiter1 = User::firstOrCreate(
            ['email' => 'waiter1@example.com'],
            [
                'name' => 'Budi Waiter',
                'password' => bcrypt('password'),
                'outlet_id' => $kemang->id,
            ]
        );
        $waiter2 = User::firstOrCreate(
            ['email' => 'waiter2@example.com'],
            [
                'name' => 'Siti Waiter',
                'password' => bcrypt('password'),
                'outlet_id' => $kemang->id,
            ]
        );
        $waiter3 = User::firstOrCreate(
            ['email' => 'waiter3@example.com'],
            [
                'name' => 'Agus Waiter',
                'password' => bcrypt('password'),
                'outlet_id' => $senopati->id,
            ]
        );

        // 3. Create Tables
        $tables = [
            ['number' => 'Meja 01', 'capacity' => 2, 'outlet_id' => $kemang->id, 'status' => 'available'],
            ['number' => 'Meja 02', 'capacity' => 4, 'outlet_id' => $kemang->id, 'status' => 'available'],
            ['number' => 'Meja 03', 'capacity' => 4, 'outlet_id' => $kemang->id, 'status' => 'available'],
            ['number' => 'Meja 04', 'capacity' => 6, 'outlet_id' => $kemang->id, 'status' => 'available'],
            ['number' => 'Meja 01', 'capacity' => 2, 'outlet_id' => $senopati->id, 'status' => 'available'],
            ['number' => 'Meja 02', 'capacity' => 4, 'outlet_id' => $senopati->id, 'status' => 'available'],
            ['number' => 'Meja 03', 'capacity' => 4, 'outlet_id' => $senopati->id, 'status' => 'available'],
        ];

        $tableModels = [];
        foreach ($tables as $t) {
            $tableModels[] = Table::create($t);
        }

        // 4. Create Customers (CRM)
        $walkIn = Customer::create([
            'name' => 'Walk-In Customer',
            'phone' => null,
            'email' => null,
            'is_member' => false,
            'loyalty_points' => 0,
        ]);

        $johnDoe = Customer::create([
            'name' => 'John Doe',
            'phone' => '081234567890',
            'email' => 'john.doe@example.com',
            'is_member' => true,
            'loyalty_points' => 150,
            'birth_date' => '1990-01-01',
        ]);

        $janeSmith = Customer::create([
            'name' => 'Jane Smith',
            'phone' => '089876543210',
            'email' => 'jane.smith@example.com',
            'is_member' => true,
            'loyalty_points' => 320,
            'birth_date' => '1995-05-12',
        ]);

        $birthdayCustomer = Customer::create([
            'name' => 'Rian Birthday Boy',
            'phone' => '08129999111',
            'email' => 'rian.birthday@example.com',
            'is_member' => true,
            'loyalty_points' => 250,
            'birth_date' => Carbon::today()->format('Y-m-d'),
        ]);

        $customer1 = Customer::create([
            'name' => 'Amanda Putri',
            'phone' => '08124444555',
            'email' => 'amanda@example.com',
            'is_member' => true,
            'loyalty_points' => 120,
            'birth_date' => '1998-05-15',
        ]);

        $customer2 = Customer::create([
            'name' => 'Joni Wijaya',
            'phone' => '08127777888',
            'email' => 'joni.wijaya@example.com',
            'is_member' => true,
            'loyalty_points' => 80,
            'birth_date' => '1992-11-20',
        ]);

        // 5. Create Couriers
        $courier1 = Courier::create([
            'name' => 'Joko Courier',
            'phone' => '08130000222',
            'vehicle_number' => 'B 3020 ABC',
            'is_active' => true,
            'outlet_id' => $kemang->id,
        ]);
        $courier2 = Courier::create([
            'name' => 'Dani Courier',
            'phone' => '08130000333',
            'vehicle_number' => 'B 6090 XYZ',
            'is_active' => true,
            'outlet_id' => $kemang->id,
        ]);

        // 6. Create Vouchers
        $voucher1 = Voucher::create([
            'code' => 'DISKONKAFE',
            'type' => 'nominal',
            'value' => 10000,
            'min_purchase' => 50000,
            'usage_limit' => 100,
            'usage_count' => 12,
            'expires_at' => Carbon::now()->addDays(30)->format('Y-m-d'),
            'is_active' => true,
        ]);
        $voucher2 = Voucher::create([
            'code' => 'PROMOAREN',
            'type' => 'percent',
            'value' => 15,
            'min_purchase' => 30000,
            'usage_limit' => 50,
            'usage_count' => 5,
            'expires_at' => Carbon::now()->addDays(15)->format('Y-m-d'),
            'is_active' => true,
        ]);

        // 7. Create Ingredients & Suppliers
        $ingredients = [
            ['name' => 'Biji Kopi Espresso Blend', 'unit' => 'g', 'purchase_price' => 150],
            ['name' => 'Fresh Milk UHT', 'unit' => 'ml', 'purchase_price' => 20],
            ['name' => 'Es Batu Kristal', 'unit' => 'g', 'purchase_price' => 5],
            ['name' => 'Palm Sugar Aren Syrup', 'unit' => 'ml', 'purchase_price' => 50],
            ['name' => 'Paper Cup 12oz', 'unit' => 'pcs', 'purchase_price' => 800],
            ['name' => 'Plastic Dome Lid', 'unit' => 'pcs', 'purchase_price' => 200],
            ['name' => 'Matcha Powder Kyoto', 'unit' => 'g', 'purchase_price' => 300],
            ['name' => 'Chocolate Powder Belgian', 'unit' => 'g', 'purchase_price' => 250],
            ['name' => 'Taro Powder', 'unit' => 'g', 'purchase_price' => 200],
            ['name' => 'Tea Leaves Earl Grey', 'unit' => 'g', 'purchase_price' => 180],
            ['name' => 'Sirup Vanilla & Caramel', 'unit' => 'ml', 'purchase_price' => 60],
            ['name' => 'Daging Sapi & Smoked Beef', 'unit' => 'g', 'purchase_price' => 220],
            ['name' => 'Chicken Katsu / Fillet', 'unit' => 'g', 'purchase_price' => 120],
            ['name' => 'Beras Pandan Wangi', 'unit' => 'g', 'purchase_price' => 18],
            ['name' => 'Spaghetti Pasta', 'unit' => 'g', 'purchase_price' => 40],
            ['name' => 'Mie & Bakso / Udang', 'unit' => 'g', 'purchase_price' => 60],
            ['name' => 'Pastry Dough Croissant', 'unit' => 'pcs', 'purchase_price' => 5000],
            ['name' => 'Frozen French Fries', 'unit' => 'g', 'purchase_price' => 35],
            ['name' => 'Waffle Batter Mix', 'unit' => 'g', 'purchase_price' => 30],
            ['name' => 'Nutella & Sweet Sauce', 'unit' => 'g', 'purchase_price' => 120],
            ['name' => 'Truffle Oil & Parmesan', 'unit' => 'ml', 'purchase_price' => 400],
            ['name' => 'Telur Ayam Segar', 'unit' => 'pcs', 'purchase_price' => 2000],
            ['name' => 'Keju Mozzarella & Cheddar', 'unit' => 'g', 'purchase_price' => 150],
            ['name' => 'Minyak Goreng & Bumbu', 'unit' => 'ml', 'purchase_price' => 25],
        ];

        $ingModels = [];
        foreach ($ingredients as $ing) {
            $ingModels[] = Ingredient::create([
                'name' => $ing['name'],
                'unit' => $ing['unit'],
                'purchase_unit' => $ing['unit'],
                'usage_unit' => $ing['unit'],
                'purchase_price' => $ing['purchase_price'],
            ]);
        }

        $supplier1 = Supplier::create([
            'name' => 'Sumatra Coffee Beans Dist.',
            'phone' => '08111222333',
            'email' => 'contact@sumatracoffee.com',
            'address' => 'Medan, Sumatera Utara',
            'contact_person' => 'Budi Santoso',
        ]);
        $supplier2 = Supplier::create([
            'name' => 'Indo Milk Foods',
            'phone' => '08222333444',
            'email' => 'sales@indomilkfoods.com',
            'address' => 'Kawasan Industri Pulogadung, Jakarta',
            'contact_person' => 'Siti Aminah',
        ]);
        $supplier3 = Supplier::create([
            'name' => 'PT Berkah Food & Bakery Supply',
            'phone' => '08333444555',
            'email' => 'order@berkahfoodsupply.co.id',
            'address' => 'Kebayoran Baru, Jakarta Selatan',
            'contact_person' => 'Hendra Setiawan',
        ]);

        foreach ($ingModels as $idx => $ing) {
            $suppId = ($idx < 6 || $idx === 9 || $idx === 10) ? $supplier1->id : (($idx === 1 || $idx === 22) ? $supplier2->id : $supplier3->id);
            
            // Seed for Kemang
            OutletIngredient::create([
                'outlet_id' => $kemang->id,
                'ingredient_id' => $ing->id,
                'stock_qty' => 50000,
                'threshold_qty' => 1000,
            ]);

            // Seed for Senopati
            OutletIngredient::create([
                'outlet_id' => $senopati->id,
                'ingredient_id' => $ing->id,
                'stock_qty' => 40000,
                'threshold_qty' => 1000,
            ]);

            StockTransaction::create([
                'outlet_id' => $kemang->id,
                'user_id' => $admin->id,
                'supplier_id' => $suppId,
                'item_type' => 'Ingredient',
                'item_id' => $ing->id,
                'qty' => 50000,
                'type' => 'set',
                'notes' => 'Initial seeder stock',
            ]);
        }

        // 8. Create Products & Recipes
        $productList = [
            // --- COFFEE ---
            [
                'name' => 'Es Kopi Aren Signature',
                'price' => 23000,
                'category' => 'Coffee',
                'description' => 'Kopi susu gula aren khas CafePOS, manis legit pas kafeinnya.',
                'recipes' => [
                    [$ingModels[0]->id, 15],  // Biji kopi
                    [$ingModels[1]->id, 120], // Fresh milk
                    [$ingModels[3]->id, 20],  // Aren
                    [$ingModels[4]->id, 1],   // Paper cup
                ],
            ],
            [
                'name' => 'Caffe Latte',
                'price' => 25000,
                'category' => 'Coffee',
                'description' => 'Perpaduan double shot espresso dan susu hangat berbusa lembut.',
                'recipes' => [
                    [$ingModels[0]->id, 18],
                    [$ingModels[1]->id, 180],
                ],
            ],
            [
                'name' => 'Cappuccino',
                'price' => 25000,
                'category' => 'Coffee',
                'description' => 'Espresso klasik dengan lapisan foam susu tebal dan taburan bubuk cokelat.',
                'recipes' => [
                    [$ingModels[0]->id, 18],
                    [$ingModels[1]->id, 150],
                ],
            ],
            [
                'name' => 'Americano / Long Black',
                'price' => 20000,
                'category' => 'Coffee',
                'description' => 'Double shot espresso dipadu air murni, kaya aroma bagi pencinta kopi sejati.',
                'recipes' => [
                    [$ingModels[0]->id, 18],
                ],
            ],
            [
                'name' => 'Caramel Macchiato',
                'price' => 28000,
                'category' => 'Coffee',
                'description' => 'Espresso beraroma vanilla halus dengan siraman saus karamel manis mewah.',
                'recipes' => [
                    [$ingModels[0]->id, 18],
                    [$ingModels[1]->id, 150],
                    [$ingModels[10]->id, 15], // Sirup vanilla/caramel
                ],
            ],
            [
                'name' => 'Avocado Coffee Float',
                'price' => 30000,
                'category' => 'Coffee',
                'description' => 'Jus alpukat kental dikombinasikan espresso shot & topping es krim vanilla.',
                'recipes' => [
                    [$ingModels[0]->id, 15],
                    [$ingModels[1]->id, 100],
                ],
            ],

            // --- NON-COFFEE ---
            [
                'name' => 'Uji Matcha Latte',
                'price' => 26000,
                'category' => 'Non-Coffee',
                'description' => 'Matcha asli Kyoto dipadukan dengan fresh milk lezat.',
                'recipes' => [
                    [$ingModels[6]->id, 10], // Matcha powder
                    [$ingModels[1]->id, 180],
                    [$ingModels[4]->id, 1],
                ],
            ],
            [
                'name' => 'Dark Chocolate Deluxe',
                'price' => 26000,
                'category' => 'Non-Coffee',
                'description' => 'Cokelat hitam kental ala Belgium dengan manis pahit pas.',
                'recipes' => [
                    [$ingModels[7]->id, 25], // Chocolate powder
                    [$ingModels[1]->id, 180],
                ],
            ],
            [
                'name' => 'Taro Velvet Latte',
                'price' => 24000,
                'category' => 'Non-Coffee',
                'description' => 'Minuman taro creamy manis gurih beraroma wangi lembut.',
                'recipes' => [
                    [$ingModels[8]->id, 25],
                    [$ingModels[1]->id, 180],
                ],
            ],
            [
                'name' => 'Fresh Lemon Iced Tea',
                'price' => 18000,
                'category' => 'Non-Coffee',
                'description' => 'Teh hitam segar dipadukan dengan sari buah lemon asli & es batu.',
                'recipes' => [
                    [$ingModels[9]->id, 8],
                    [$ingModels[2]->id, 50],
                ],
            ],
            [
                'name' => 'Earl Grey Milk Tea',
                'price' => 22000,
                'category' => 'Non-Coffee',
                'description' => 'Teh Earl Grey beraroma citrus dipadukan susu dan gula aren pilihan.',
                'recipes' => [
                    [$ingModels[9]->id, 10],
                    [$ingModels[1]->id, 150],
                    [$ingModels[3]->id, 15],
                ],
            ],

            // --- FOOD (MAIN COURSE) ---
            [
                'name' => 'Nasi Goreng Spesial CafePOS',
                'price' => 35000,
                'category' => 'Food',
                'description' => 'Nasi goreng khas kafe dengan telur mata sapi, sosis, ayam suwir & kerupuk renyah.',
                'recipes' => [
                    [$ingModels[13]->id, 200], // Beras
                    [$ingModels[21]->id, 1],   // Telur
                    [$ingModels[12]->id, 50],  // Chicken
                    [$ingModels[23]->id, 15],  // Minyak/Bumbu
                ],
            ],
            [
                'name' => 'Spaghetti Carbonara Smoked Beef',
                'price' => 38000,
                'category' => 'Food',
                'description' => 'Pasta spaghetti renyah creamy dengan keju parmesan gurih & irisan smoked beef.',
                'recipes' => [
                    [$ingModels[14]->id, 120], // Spaghetti
                    [$ingModels[11]->id, 40],  // Smoked beef
                    [$ingModels[22]->id, 30],  // Keju
                    [$ingModels[1]->id, 80],   // Milk
                ],
            ],
            [
                'name' => 'Chicken Katsu Don Bowl',
                'price' => 36000,
                'category' => 'Food',
                'description' => 'Nasi hangat topping chicken katsu renyah, telur dadar lembut & saus donburi.',
                'recipes' => [
                    [$ingModels[13]->id, 200],
                    [$ingModels[12]->id, 120], // Katsu
                    [$ingModels[21]->id, 1],
                ],
            ],
            [
                'name' => 'Beef Teriyaki Rice Bowl',
                'price' => 42000,
                'category' => 'Food',
                'description' => 'Irisan daging sapi empuk tumis saus teriyaki gurih manis di atas nasi hangat.',
                'recipes' => [
                    [$ingModels[13]->id, 200],
                    [$ingModels[11]->id, 100], // Beef
                    [$ingModels[23]->id, 20],
                ],
            ],
            [
                'name' => 'Mie Goreng Mamak',
                'price' => 32000,
                'category' => 'Food',
                'description' => 'Mie goreng rempah pedas manis dengan udang segar, sosis & telur iris.',
                'recipes' => [
                    [$ingModels[15]->id, 150], // Mie/Bakso
                    [$ingModels[21]->id, 1],
                ],
            ],

            // --- SNACKS (LIGHT BITES) ---
            [
                'name' => 'Butter Croissant',
                'price' => 22000,
                'category' => 'Snacks',
                'description' => 'Pastry renyah berlapis khas Prancis dengan aroma mentega murni lezat.',
                'recipes' => [
                    [$ingModels[16]->id, 1], // Pastry Croissant
                ],
            ],
            [
                'name' => 'French Fries Supreme',
                'price' => 20000,
                'category' => 'Snacks',
                'description' => 'Kentang goreng renyah bumbu gurih disajikan dengan saus mayo & sambal.',
                'recipes' => [
                    [$ingModels[17]->id, 150], // Fries
                    [$ingModels[23]->id, 20],
                ],
            ],
            [
                'name' => 'Truffle Parmesan Fries',
                'price' => 28000,
                'category' => 'Snacks',
                'description' => 'Kentang goreng dengan aroma truffle oil harum & taburan keju parmesan parut.',
                'recipes' => [
                    [$ingModels[17]->id, 150],
                    [$ingModels[20]->id, 10], // Truffle & Parmesan
                ],
            ],
            [
                'name' => 'Beef & Cheese Toast',
                'price' => 25000,
                'category' => 'Snacks',
                'description' => 'Roti panggang lezat dengan isi smoked beef juicy & keju leleh lumer.',
                'recipes' => [
                    [$ingModels[11]->id, 30],
                    [$ingModels[22]->id, 30],
                ],
            ],
            [
                'name' => 'Mix Snack Platter',
                'price' => 35000,
                'category' => 'Snacks',
                'description' => 'Paket komplit kentang goreng, sosis panggang, chicken nugget & onion rings.',
                'recipes' => [
                    [$ingModels[17]->id, 100],
                    [$ingModels[12]->id, 60],
                ],
            ],

            // --- DESSERT ---
            [
                'name' => 'Banana Nutella Waffle',
                'price' => 28000,
                'category' => 'Dessert',
                'description' => 'Waffle renyah dipadu potongan pisang segar & lelehan sirup Nutella melimpah.',
                'recipes' => [
                    [$ingModels[18]->id, 100], // Waffle batter
                    [$ingModels[19]->id, 30],  // Nutella
                ],
            ],
            [
                'name' => 'Croffle Maple Syrup',
                'price' => 24000,
                'category' => 'Dessert',
                'description' => 'Croissant waffle renyah di luar, lembut di dalam disiram sirup maple hangat.',
                'recipes' => [
                    [$ingModels[16]->id, 1], // Croissant
                ],
            ],
            [
                'name' => 'Chocolate Lava Cake',
                'price' => 25000,
                'category' => 'Dessert',
                'description' => 'Cake cokelat hangat dengan lelehan cokelat di dalamnya + es krim vanilla.',
                'recipes' => [
                    [$ingModels[7]->id, 40],
                    [$ingModels[19]->id, 20],
                ],
            ],
        ];

        $allProductModels = [];

        foreach ($productList as $pData) {
            $prod = Product::create([
                'name' => $pData['name'],
                'price' => $pData['price'],
                'category' => $pData['category'],
                'description' => $pData['description'],
                'is_active' => true,
            ]);

            foreach ($pData['recipes'] as $rItem) {
                Recipe::create([
                    'product_id' => $prod->id,
                    'ingredient_id' => $rItem[0],
                    'usage_qty' => $rItem[1],
                ]);
            }

            // Seed direct retail stock in OutletProduct for Kemang & Senopati
            OutletProduct::create([
                'outlet_id' => $kemang->id,
                'product_id' => $prod->id,
                'stock_qty' => 100,
                'threshold_qty' => 10,
            ]);

            OutletProduct::create([
                'outlet_id' => $senopati->id,
                'product_id' => $prod->id,
                'stock_qty' => 100,
                'threshold_qty' => 10,
            ]);

            $allProductModels[] = $prod;
        }

        // Keep easy variable reference for existing promos or references
        $kopiAren = $allProductModels[0];
        $matcha = $allProductModels[6];

        // Seed Modifiers
        Modifier::create([
            'name' => 'Extra Shot Espresso',
            'price' => 5000.00,
            'ingredient_id' => $ingModels[0]->id, // Biji Kopi Espresso Blend
            'usage_qty' => 9.0,
        ]);

        Modifier::create([
            'name' => 'Oat Milk Upgrade',
            'price' => 8000.00,
            'ingredient_id' => $ingModels[1]->id, // Fresh Milk UHT
            'usage_qty' => 150.0,
        ]);

        Modifier::create([
            'name' => 'Extra Syrup Aren',
            'price' => 3000.00,
            'ingredient_id' => $ingModels[3]->id, // Palm Sugar Aren Syrup
            'usage_qty' => 15.0,
        ]);

        Modifier::create([
            'name' => 'Extra Keju Mozzarella',
            'price' => 6000.00,
            'ingredient_id' => $ingModels[22]->id,
            'usage_qty' => 30.0,
        ]);

        Modifier::create([
            'name' => 'Extra Telur Mata Sapi',
            'price' => 5000.00,
            'ingredient_id' => $ingModels[21]->id,
            'usage_qty' => 1.0,
        ]);

        // Seed Promos
        Promo::create([
            'name' => 'Diskon Pembukaan 10%',
            'type' => 'percent',
            'value' => 10.00,
            'min_purchase' => 50000.00,
            'product_id' => null,
            'is_active' => true,
        ]);

        Promo::create([
            'name' => 'Potongan Weekend Rp 15.000',
            'type' => 'nominal',
            'value' => 15000.00,
            'min_purchase' => 100000.00,
            'product_id' => null,
            'is_active' => true,
        ]);

        // 9. Create Purchase Orders (PO / GRN)
        $poReceived = PurchaseOrder::create([
            'po_number' => 'PO-20260710-001',
            'outlet_id' => $kemang->id,
            'supplier_id' => $supplier1->id,
            'status' => 'received',
            'total_amount' => 1500000,
            'notes' => 'Pemesanan biji kopi espresso blend restock bulanan.',
        ]);
        PurchaseOrderItem::create([
            'purchase_order_id' => $poReceived->id,
            'ingredient_id' => $ingModels[0]->id,
            'qty' => 10000,
            'price' => 150,
            'subtotal' => 1500000,
        ]);

        $poSent = PurchaseOrder::create([
            'po_number' => 'PO-20260710-002',
            'outlet_id' => $kemang->id,
            'supplier_id' => $supplier2->id,
            'status' => 'sent',
            'total_amount' => 400000,
            'notes' => 'Pesan susu UHT fresh milk 20 liter.',
        ]);
        PurchaseOrderItem::create([
            'purchase_order_id' => $poSent->id,
            'ingredient_id' => $ingModels[1]->id,
            'qty' => 20000,
            'price' => 20,
            'subtotal' => 400000,
        ]);

        PurchaseOrder::create([
            'po_number' => 'PO-20260710-003',
            'outlet_id' => $kemang->id,
            'supplier_id' => $supplier1->id,
            'status' => 'draft',
            'total_amount' => 100000,
            'notes' => 'Draft pesanan lid dome plastik.',
        ]);

        // 10. Seed Transaction Sales History (Owner Analytics Data)
        $now = Carbon::now();
        $invoiceCounter = 1001;

        for ($day = 3; $day >= 0; $day--) {
            $date = (clone $now)->subDays($day);
            $hours = [10, 11, 13, 14, 15, 17, 19, 20];
            shuffle($hours);
            $numOrders = $day === 0 ? 5 : rand(4, 7);

            for ($i = 0; $i < $numOrders; $i++) {
                $orderHour = array_pop($hours) ?? 12;
                $orderTime = (clone $date)->setHour($orderHour)->setMinute(rand(0, 59))->setSecond(0);

                $cashier = $i % 2 === 0 ? $cashier1 : $cashier2;
                $outlet = $cashier->outlet_id === $kemang->id ? $kemang : $senopati;
                
                $type = $i % 3 === 0 ? 'dine_in' : ($i % 3 === 1 ? 'take_away' : 'delivery');
                $table = $type === 'dine_in' ? $tableModels[rand(0, count($tableModels) - 1)] : null;
                $waiter = $type === 'dine_in' ? ($i % 2 === 0 ? $waiter1 : $waiter2) : null;
                $courier = $type === 'delivery' ? $courier1 : null;
                
                $items = [];
                $subtotal = 0.0;

                // Pick 1 to 3 random products for each transaction
                $selectedProds = array_rand($allProductModels, rand(1, 3));
                if (!is_array($selectedProds)) {
                    $selectedProds = [$selectedProds];
                }

                foreach ($selectedProds as $pIdx) {
                    $targetProduct = $allProductModels[$pIdx];
                    $qty = rand(1, 2);
                    $sub = $qty * (float)$targetProduct->price;
                    $subtotal += $sub;

                    $variant = null;
                    if ($targetProduct->category === 'Coffee' || $targetProduct->category === 'Non-Coffee') {
                        $variant = rand(0, 1) === 1 ? 'ice' : 'hot';
                    }

                    $items[] = [
                        'product_id' => $targetProduct->id,
                        'qty' => $qty,
                        'price' => (float)$targetProduct->price,
                        'subtotal' => $sub,
                        'variant' => $variant,
                    ];
                }

                $customer = $i % 3 === 0 ? $customer1 : ($i % 3 === 1 ? $customer2 : null);

                $discount = 0.0;
                if ($customer && $i % 4 === 0) {
                    $discount = 10000.0;
                }

                $total = max(0.0, $subtotal - $discount);
                $invoiceNum = "INV-" . $orderTime->format('Ymd') . "-" . $invoiceCounter++;

                $transaction = Transaction::create([
                    'outlet_id' => $outlet->id,
                    'user_id' => $cashier->id,
                    'customer_id' => $customer?->id,
                    'table_id' => $table?->id,
                    'waiter_id' => $waiter?->id,
                    'courier_id' => $courier?->id,
                    'transaction_number' => $invoiceNum,
                    'order_type' => $type,
                    'payment_method' => rand(0, 1) === 1 ? 'qris' : 'cash',
                    'discount_amount' => $discount,
                    'total_amount' => $total,
                    'tax_amount' => $total * 0.1, // 10% tax
                    'service_charge_amount' => $type === 'dine_in' ? $total * 0.05 : 0, // 5% service charge for Dine In
                    'status' => 'success',
                    'delivery_status' => $type === 'delivery' ? 'delivered' : null,
                    'created_at' => $orderTime,
                    'updated_at' => $orderTime,
                ]);

                foreach ($items as $item) {
                    TransactionItem::create([
                        'transaction_id' => $transaction->id,
                        'product_id' => $item['product_id'],
                        'qty' => $item['qty'],
                        'price' => $item['price'],
                        'subtotal' => $item['subtotal'],
                        'variant' => $item['variant'],
                        'kitchen_status' => 'served',
                        'created_at' => $orderTime,
                        'updated_at' => $orderTime,
                    ]);
                }
            }
        }
    }
}

