<?php

namespace Database\Seeders;

use App\Models\Restaurant;
use App\Models\Branch;
use App\Models\Customer;
use App\Models\CustomerAddress;
use App\Models\MenuItem;
use App\Models\Menu;
use App\Models\ItemCategory;
use App\Models\Currency;
use App\Models\GlobalCurrency;
use App\Models\Country;
use App\Models\Package;
use App\Models\User;
use App\Models\Role;
use App\Models\Area;
use App\Models\Table;
use App\Models\DeliveryExecutive;
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;

class WebOrderingDemoSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // Get required default data
        $country = Country::where('countries_code', 'MY')->first() ?? Country::first();
        $package = Package::first();

        if (!$country || !$package) {
            $this->command->error('Please seed Country and Package first!');
            return;
        }

        // Get or create Malaysian Ringgit (MYR) currency
        $myrCurrency = GlobalCurrency::firstOrCreate(
            ['currency_code' => 'MYR'],
            [
                'currency_name' => 'Ringgit',
                'currency_symbol' => 'RM',
                'currency_code' => 'MYR',
                'currency_position' => 'left',
                'no_of_decimal' => 2,
                'thousand_separator' => ',',
                'decimal_separator' => '.',
                'status' => 1,
            ]
        );

        // Restaurant data
        $restaurantsData = [
            [
                'name' => 'Pizza Paradise',
                'email' => 'pizza@paradise.com',
                'phone' => '+1234567890',
                'restaurant_name' => 'Pizza Paradise',
                'description' => 'Authentic Italian pizzas and pastas with fresh ingredients',
                'branches' => [
                    [
                        'name' => 'Downtown Branch',
                        'address' => '123 Main Street, Downtown',
                        'phone' => '+1234567891',
                        'email' => 'downtown@pizzaparadise.com',
                        'lat' => 40.7128,
                        'lng' => -74.0060,
                    ],
                    [
                        'name' => 'Uptown Branch',
                        'address' => '456 Park Avenue, Uptown',
                        'phone' => '+1234567892',
                        'email' => 'uptown@pizzaparadise.com',
                        'lat' => 40.7580,
                        'lng' => -73.9855,
                    ],
                ],
                'menu_items' => [
                    ['name' => 'Margherita Pizza', 'price' => 12.99, 'category' => 'Main Course', 'type' => MenuItem::VEG],
                    ['name' => 'Pepperoni Pizza', 'price' => 14.99, 'category' => 'Main Course', 'type' => MenuItem::NONVEG],
                    ['name' => 'BBQ Chicken Pizza', 'price' => 16.99, 'category' => 'Main Course', 'type' => MenuItem::NONVEG],
                    ['name' => 'Veggie Supreme Pizza', 'price' => 13.99, 'category' => 'Main Course', 'type' => MenuItem::VEG],
                    ['name' => 'Spaghetti Carbonara', 'price' => 15.99, 'category' => 'Main Course', 'type' => MenuItem::NONVEG],
                    ['name' => 'Fettuccine Alfredo', 'price' => 14.99, 'category' => 'Main Course', 'type' => MenuItem::VEG],
                    ['name' => 'Caesar Salad', 'price' => 8.99, 'category' => 'Salads', 'type' => MenuItem::NONVEG],
                    ['name' => 'Garlic Bread', 'price' => 5.99, 'category' => 'Sides', 'type' => MenuItem::VEG],
                    ['name' => 'Tiramisu', 'price' => 7.99, 'category' => 'Desserts', 'type' => MenuItem::VEG],
                    ['name' => 'Coca Cola', 'price' => 2.99, 'category' => 'Beverages', 'type' => MenuItem::VEG],
                ],
            ],
            [
                'name' => 'Burger Hub',
                'email' => 'info@burgerhub.com',
                'phone' => '+1987654321',
                'restaurant_name' => 'Burger Hub',
                'description' => 'Gourmet burgers and fries made with premium ingredients',
                'branches' => [
                    [
                        'name' => 'Central Branch',
                        'address' => '789 Broadway, Central',
                        'phone' => '+1987654322',
                        'email' => 'central@burgerhub.com',
                        'lat' => 40.7505,
                        'lng' => -73.9934,
                    ],
                ],
                'menu_items' => [
                    ['name' => 'Classic Burger', 'price' => 10.99, 'category' => 'Fast Food', 'type' => MenuItem::NONVEG],
                    ['name' => 'Veggie Burger', 'price' => 9.99, 'category' => 'Fast Food', 'type' => MenuItem::VEG],
                    ['name' => 'Double Cheeseburger', 'price' => 13.99, 'category' => 'Fast Food', 'type' => MenuItem::NONVEG],
                    ['name' => 'Chicken Burger', 'price' => 11.99, 'category' => 'Fast Food', 'type' => MenuItem::NONVEG],
                    ['name' => 'French Fries', 'price' => 4.99, 'category' => 'Sides', 'type' => MenuItem::VEG],
                    ['name' => 'Onion Rings', 'price' => 5.99, 'category' => 'Sides', 'type' => MenuItem::VEG],
                    ['name' => 'Chicken Wings', 'price' => 8.99, 'category' => 'Starters', 'type' => MenuItem::NONVEG],
                    ['name' => 'Chocolate Shake', 'price' => 6.99, 'category' => 'Beverages', 'type' => MenuItem::VEG],
                    ['name' => 'Apple Pie', 'price' => 5.99, 'category' => 'Desserts', 'type' => MenuItem::VEG],
                ],
            ],
            [
                'name' => 'Sushi World',
                'email' => 'hello@sushiworld.com',
                'phone' => '+1122334455',
                'restaurant_name' => 'Sushi World',
                'description' => 'Fresh sushi and Japanese cuisine in a modern setting',
                'branches' => [
                    [
                        'name' => 'Riverside Branch',
                        'address' => '321 River Road, Riverside',
                        'phone' => '+1122334456',
                        'email' => 'riverside@sushiworld.com',
                        'lat' => 40.7614,
                        'lng' => -73.9776,
                    ],
                    [
                        'name' => 'Mall Branch',
                        'address' => '555 Shopping Mall, 2nd Floor',
                        'phone' => '+1122334457',
                        'email' => 'mall@sushiworld.com',
                        'lat' => 40.7489,
                        'lng' => -73.9680,
                    ],
                ],
                'menu_items' => [
                    ['name' => 'Salmon Sushi', 'price' => 8.99, 'category' => 'Main Course', 'type' => MenuItem::NONVEG],
                    ['name' => 'Tuna Roll', 'price' => 9.99, 'category' => 'Main Course', 'type' => MenuItem::NONVEG],
                    ['name' => 'California Roll', 'price' => 7.99, 'category' => 'Main Course', 'type' => MenuItem::VEG],
                    ['name' => 'Dragon Roll', 'price' => 12.99, 'category' => 'Main Course', 'type' => MenuItem::NONVEG],
                    ['name' => 'Miso Soup', 'price' => 4.99, 'category' => 'Soups', 'type' => MenuItem::VEG],
                    ['name' => 'Chicken Teriyaki', 'price' => 15.99, 'category' => 'Main Course', 'type' => MenuItem::NONVEG],
                    ['name' => 'Edamame', 'price' => 5.99, 'category' => 'Starters', 'type' => MenuItem::VEG],
                    ['name' => 'Green Tea', 'price' => 2.99, 'category' => 'Beverages', 'type' => MenuItem::VEG],
                    ['name' => 'Mochi Ice Cream', 'price' => 6.99, 'category' => 'Desserts', 'type' => MenuItem::VEG],
                ],
            ],
            [
                'name' => 'Cafe Mocha',
                'email' => 'contact@cafemocha.com',
                'phone' => '+1555666777',
                'restaurant_name' => 'Cafe Mocha',
                'description' => 'Cozy coffee shop with artisanal coffee and fresh pastries',
                'branches' => [
                    [
                        'name' => 'Cafe Downtown',
                        'address' => '999 Coffee Street, Downtown',
                        'phone' => '+1555666778',
                        'email' => 'downtown@cafemocha.com',
                        'lat' => 40.7282,
                        'lng' => -73.9942,
                    ],
                ],
                'menu_items' => [
                    ['name' => 'Espresso', 'price' => 3.99, 'category' => 'Beverages', 'type' => MenuItem::VEG],
                    ['name' => 'Cappuccino', 'price' => 4.99, 'category' => 'Beverages', 'type' => MenuItem::VEG],
                    ['name' => 'Latte', 'price' => 4.99, 'category' => 'Beverages', 'type' => MenuItem::VEG],
                    ['name' => 'Americano', 'price' => 3.99, 'category' => 'Beverages', 'type' => MenuItem::VEG],
                    ['name' => 'Croissant', 'price' => 4.99, 'category' => 'Snacks', 'type' => MenuItem::VEG],
                    ['name' => 'Blueberry Muffin', 'price' => 3.99, 'category' => 'Snacks', 'type' => MenuItem::VEG],
                    ['name' => 'Bagel with Cream Cheese', 'price' => 5.99, 'category' => 'Snacks', 'type' => MenuItem::VEG],
                    ['name' => 'Chocolate Cake', 'price' => 6.99, 'category' => 'Desserts', 'type' => MenuItem::VEG],
                    ['name' => 'Sandwich Club', 'price' => 8.99, 'category' => 'Main Course', 'type' => MenuItem::NONVEG],
                    ['name' => 'Fresh Orange Juice', 'price' => 4.99, 'category' => 'Juices', 'type' => MenuItem::VEG],
                ],
            ],
            [
                'name' => 'Thai Garden',
                'email' => 'info@thaigarden.com',
                'phone' => '+1444555666',
                'restaurant_name' => 'Thai Garden',
                'description' => 'Authentic Thai cuisine with bold flavors and aromatic spices',
                'branches' => [
                    [
                        'name' => 'Garden Branch',
                        'address' => '777 Garden Lane, Park District',
                        'phone' => '+1444555667',
                        'email' => 'garden@thaigarden.com',
                        'lat' => 40.7851,
                        'lng' => -73.9683,
                    ],
                    [
                        'name' => 'City Center Branch',
                        'address' => '888 City Center Plaza',
                        'phone' => '+1444555668',
                        'email' => 'citycenter@thaigarden.com',
                        'lat' => 40.7589,
                        'lng' => -73.9851,
                    ],
                ],
                'menu_items' => [
                    ['name' => 'Pad Thai', 'price' => 13.99, 'category' => 'Main Course', 'type' => MenuItem::NONVEG],
                    ['name' => 'Green Curry', 'price' => 14.99, 'category' => 'Main Course', 'type' => MenuItem::NONVEG],
                    ['name' => 'Tom Yum Soup', 'price' => 9.99, 'category' => 'Soups', 'type' => MenuItem::NONVEG],
                    ['name' => 'Spring Rolls', 'price' => 6.99, 'category' => 'Starters', 'type' => MenuItem::VEG],
                    ['name' => 'Massaman Curry', 'price' => 15.99, 'category' => 'Main Course', 'type' => MenuItem::NONVEG],
                    ['name' => 'Thai Fried Rice', 'price' => 12.99, 'category' => 'Rice', 'type' => MenuItem::NONVEG],
                    ['name' => 'Mango Sticky Rice', 'price' => 7.99, 'category' => 'Desserts', 'type' => MenuItem::VEG],
                    ['name' => 'Thai Iced Tea', 'price' => 4.99, 'category' => 'Beverages', 'type' => MenuItem::VEG],
                    ['name' => 'Som Tam (Papaya Salad)', 'price' => 8.99, 'category' => 'Salads', 'type' => MenuItem::VEG],
                ],
            ],
        ];

        // Create restaurants with branches and menu items
        foreach ($restaurantsData as $restaurantData) {
            $restaurant = Restaurant::create([
                'name' => $restaurantData['name'],
                'email' => $restaurantData['email'],
                'phone_number' => $restaurantData['phone'],
                'restaurant_name' => $restaurantData['restaurant_name'],
                'address' => fake()->address(),
                'timezone' => 'Asia/Kuala_Lumpur',
                'theme_hex' => '#A78BFA',
                'theme_rgb' => '167, 139, 250',
                'currency_id' => $myrCurrency->id,
                'country_id' => $country->id,
                'package_id' => $package->id,
                'package_type' => 'annual',
                'is_active' => true,
                'hash' => Str::random(32),
                'customer_site_language' => 'en',
                'about_us' => Restaurant::ABOUT_US_DEFAULT_TEXT,
            ]);

            // Create roles for this restaurant
            $this->createRoles($restaurant);

            // Create admin user for this restaurant
            $this->createAdminUser($restaurant, $restaurantData);

            $this->command->info("Created restaurant: {$restaurant->name}");

            // Create branches for this restaurant
            foreach ($restaurantData['branches'] as $branchData) {
                // Use withoutEvents to prevent automatic QR code generation
                $branch = Branch::withoutEvents(function () use ($restaurantData, $restaurant, $branchData) {
                    return Branch::create([
                        'name' => $branchData['name'],
                        'address' => $branchData['address'],
                        'restaurant_id' => $restaurant->id,
                        'unique_hash' => Str::random(32),
                        'lat' => $branchData['lat'],
                        'lng' => $branchData['lng'],
                    ]);
                });

                $this->command->info("  Created branch: {$branch->name}");

                // Try to generate QR code (skip if GD extension not available)
                try {
                    if (extension_loaded('gd')) {
                        $branch->generateQrCode();
                    }
                } catch (\Exception $e) {
                    // Silently skip QR generation if GD not available
                }

                // Create menu for this branch
                $menu = Menu::create([
                    'menu_name' => "{$restaurant->restaurant_name} Menu",
                    'branch_id' => $branch->id,
                ]);

                // Create item categories and menu items
                $this->createMenuItems($branch, $menu, $restaurantData['menu_items']);

                // Create areas for this branch
                $this->createAreas($branch);

                // Create tables with QR codes for this branch
                $this->createTables($branch);

                // Create staff for this branch
                $this->createStaff($branch, $restaurant);

                // Create delivery executives for this branch
                $this->createDeliveryExecutives($branch);

                // Create KOT settings for this branch
                $this->createKotSettings($branch);
            }
        }

        // Create restaurant-specific currencies (MYR)
        foreach (Restaurant::whereIn('id', Restaurant::pluck('id')->toArray())->get() as $restaurant) {
            $this->createRestaurantCurrency($restaurant, $myrCurrency);
        }

        // Create customers with addresses
        $this->createCustomers();

        $this->command->info('');
        $this->command->info('✅ Demo data seeded successfully!');
        $this->command->info('');
        $this->command->info('Summary:');
        $this->command->info('- ' . Restaurant::count() . ' Restaurants');
        $this->command->info('- ' . Branch::count() . ' Branches');
        $this->command->info('- ' . MenuItem::count() . ' Menu Items');
        $this->command->info('- ' . Customer::count() . ' Customers');
        $this->command->info('- ' . Area::count() . ' Areas');
        $this->command->info('- ' . Table::count() . ' Tables (with QR codes)');
        $this->command->info('- ' . User::whereHas('roles')->count() . ' Staff Members');
        $this->command->info('- ' . DeliveryExecutive::count() . ' Delivery Executives');
    }

    /**
     * Create menu items for a branch
     */
    private function createMenuItems(Branch $branch, Menu $menu, array $menuItemsData): void
    {
        // Create categories map to avoid duplicates
        $categories = [];

        foreach ($menuItemsData as $itemData) {
            $categoryName = $itemData['category'];

            // Get or create category
            if (!isset($categories[$categoryName])) {
                $category = ItemCategory::firstOrCreate(
                    [
                        'category_name' => $categoryName,
                        'branch_id' => $branch->id,
                    ],
                    [
                        'category_name' => $categoryName,
                        'branch_id' => $branch->id,
                    ]
                );
                $categories[$categoryName] = $category;
            } else {
                $category = $categories[$categoryName];
            }

            // Create menu item
            MenuItem::create([
                'item_name' => $itemData['name'],
                'menu_id' => $menu->id,
                'branch_id' => $branch->id,
                'item_category_id' => $category->id,
                'type' => $itemData['type'],
                'price' => $itemData['price'],
                'description' => "Delicious {$itemData['name']} - freshly prepared",
                'preparation_time' => rand(15, 30),
                'show_on_customer_site' => true,
            ]);
        }
    }

    /**
     * Create demo customers with addresses
     */
    private function createCustomers(): void
    {
        $customersData = [
            [
                'name' => 'John Smith',
                'email' => 'john.smith@example.com',
                'phone' => '+12015551234',
                'phone_code' => '+1',
                'addresses' => [
                    [
                        'address' => '100 Main Street, Apt 5B',
                        'city' => 'New York',
                        'state' => 'NY',
                        'zip' => '10001',
                        'lat' => 40.7128,
                        'lng' => -74.0060,
                    ],
                ],
            ],
            [
                'name' => 'Sarah Johnson',
                'email' => 'sarah.j@example.com',
                'phone' => '+12015552345',
                'phone_code' => '+1',
                'addresses' => [
                    [
                        'address' => '250 Park Avenue, Unit 12',
                        'city' => 'New York',
                        'state' => 'NY',
                        'zip' => '10017',
                        'lat' => 40.7580,
                        'lng' => -73.9855,
                    ],
                    [
                        'address' => '500 Broadway, Floor 3',
                        'city' => 'New York',
                        'state' => 'NY',
                        'zip' => '10003',
                        'lat' => 40.7505,
                        'lng' => -73.9934,
                    ],
                ],
            ],
            [
                'name' => 'Michael Chen',
                'email' => 'michael.chen@example.com',
                'phone' => '+12015553456',
                'phone_code' => '+1',
                'addresses' => [
                    [
                        'address' => '750 River Road, Apt 8A',
                        'city' => 'New York',
                        'state' => 'NY',
                        'zip' => '10025',
                        'lat' => 40.7614,
                        'lng' => -73.9776,
                    ],
                ],
            ],
            [
                'name' => 'Emily Davis',
                'email' => 'emily.davis@example.com',
                'phone' => '+12015554567',
                'phone_code' => '+1',
                'addresses' => [
                    [
                        'address' => '888 Coffee Street, Suite 200',
                        'city' => 'New York',
                        'state' => 'NY',
                        'zip' => '10013',
                        'lat' => 40.7282,
                        'lng' => -73.9942,
                    ],
                ],
            ],
            [
                'name' => 'David Wilson',
                'email' => 'david.wilson@example.com',
                'phone' => '+12015555678',
                'phone_code' => '+1',
                'addresses' => [
                    [
                        'address' => '999 Garden Lane, House 15',
                        'city' => 'New York',
                        'state' => 'NY',
                        'zip' => '10031',
                        'lat' => 40.7851,
                        'lng' => -73.9683,
                    ],
                    [
                        'address' => '777 City Center Plaza, Office 45',
                        'city' => 'New York',
                        'state' => 'NY',
                        'zip' => '10019',
                        'lat' => 40.7589,
                        'lng' => -73.9851,
                    ],
                ],
            ],
        ];

        // Get first restaurant for customer assignment
        $firstRestaurant = Restaurant::first();

        foreach ($customersData as $customerData) {
            $customer = Customer::firstOrCreate(
                [
                    'email' => $customerData['email'],
                    'restaurant_id' => $firstRestaurant->id,
                ],
                [
                    'name' => $customerData['name'],
                    'email' => $customerData['email'],
                    'phone' => $customerData['phone'],
                    'phone_code' => $customerData['phone_code'],
                    'restaurant_id' => $firstRestaurant->id,
                ]
            );

            $this->command->info("  Created customer: {$customer->name}");

            // Create addresses for this customer
            foreach ($customerData['addresses'] as $addressData) {
                CustomerAddress::create([
                    'customer_id' => $customer->id,
                    'address' => $addressData['address'],
                    'city' => $addressData['city'],
                    'state' => $addressData['state'],
                    'zip' => $addressData['zip'],
                    'lat' => $addressData['lat'],
                    'lng' => $addressData['lng'],
                ]);
            }
        }
    }

    /**
     * Create roles for a restaurant
     */
    private function createRoles(Restaurant $restaurant): void
    {
        // Create admin role
        Role::firstOrCreate(
            ['name' => 'Admin_' . $restaurant->id],
            [
                'name' => 'Admin_' . $restaurant->id,
                'display_name' => 'Admin',
                'guard_name' => 'web',
                'restaurant_id' => $restaurant->id,
            ]
        );

        // Create waiter role
        Role::firstOrCreate(
            ['name' => 'Waiter_' . $restaurant->id],
            [
                'name' => 'Waiter_' . $restaurant->id,
                'display_name' => 'Waiter',
                'guard_name' => 'web',
                'restaurant_id' => $restaurant->id,
            ]
        );

        // Create branch head role
        Role::firstOrCreate(
            ['name' => 'Branch Head_' . $restaurant->id],
            [
                'name' => 'Branch Head_' . $restaurant->id,
                'display_name' => 'Branch Head',
                'guard_name' => 'web',
                'restaurant_id' => $restaurant->id,
            ]
        );

        // Create chef role
        Role::firstOrCreate(
            ['name' => 'Chef_' . $restaurant->id],
            [
                'name' => 'Chef_' . $restaurant->id,
                'display_name' => 'Chef',
                'guard_name' => 'web',
                'restaurant_id' => $restaurant->id,
            ]
        );

        // Assign all permissions to admin role
        $adminRole = Role::where('name', 'Admin_' . $restaurant->id)->first();
        if ($adminRole) {
            $allPermissions = \Spatie\Permission\Models\Permission::get()->pluck('name')->toArray();
            $adminRole->syncPermissions($allPermissions);
        }
    }

    /**
     * Create admin user for a restaurant
     */
    private function createAdminUser(Restaurant $restaurant, array $restaurantData): void
    {
        // Generate unique admin email based on restaurant ID to avoid conflicts
        $adminEmail = 'admin' . $restaurant->id . '@' . str_replace(['http://', 'https://', 'www.'], '', parse_url($restaurant->email, PHP_URL_HOST) ?? str_replace('@', '', $restaurant->email));
        
        // If email parsing failed, use a simple format with restaurant ID
        if (!filter_var($adminEmail, FILTER_VALIDATE_EMAIL)) {
            $domain = str_replace(['@', '.'], ['_', '_'], $restaurant->email);
            $adminEmail = 'admin' . $restaurant->id . '@' . $domain . '.demo';
        }

        // Check if user already exists by email (unique constraint)
        $admin = User::where('email', $adminEmail)->first();
        
        if (!$admin) {
            $admin = User::create([
                'name' => $restaurantData['restaurant_name'] . ' Admin',
                'email' => $adminEmail,
                'password' => bcrypt('123456'),
                'restaurant_id' => $restaurant->id,
            ]);
        } else {
            // Update existing user to ensure it's linked to this restaurant
            $admin->restaurant_id = $restaurant->id;
            $admin->name = $restaurantData['restaurant_name'] . ' Admin';
            $admin->password = bcrypt('123456');
            $admin->save();
        }

        // Assign admin role
        $adminRole = Role::where('name', 'Admin_' . $restaurant->id)->first();
        if ($adminRole) {
            if (!$admin->hasRole($adminRole)) {
                $admin->assignRole($adminRole);
            }
        }

        $this->command->info("  Created/Updated admin user: {$admin->email} (password: 123456)");
    }

    /**
     * Create restaurant-specific currency
     */
    private function createRestaurantCurrency(Restaurant $restaurant, GlobalCurrency $globalCurrency): void
    {
        $currency = Currency::where('restaurant_id', $restaurant->id)
            ->where('currency_code', $globalCurrency->currency_code)
            ->first();

        if (!$currency) {
            $currency = new Currency();
            $currency->currency_name = $globalCurrency->currency_name;
            $currency->currency_symbol = $globalCurrency->currency_symbol;
            $currency->currency_code = $globalCurrency->currency_code;
            $currency->restaurant_id = $restaurant->id;
            $currency->currency_position = $globalCurrency->currency_position ?? 'left';
            $currency->no_of_decimal = $globalCurrency->no_of_decimal ?? 2;
            $currency->thousand_separator = $globalCurrency->thousand_separator ?? ',';
            $currency->decimal_separator = $globalCurrency->decimal_separator ?? '.';
            $currency->save();
        }
    }

    /**
     * Create areas for a branch
     */
    private function createAreas(Branch $branch): void
    {
        $areas = [
            ['area_name' => 'Indoor Dining', 'branch_id' => $branch->id],
            ['area_name' => 'Outdoor Patio', 'branch_id' => $branch->id],
            ['area_name' => 'Private Room', 'branch_id' => $branch->id],
            ['area_name' => 'Bar Area', 'branch_id' => $branch->id],
        ];

        foreach ($areas as $areaData) {
            Area::firstOrCreate(
                [
                    'area_name' => $areaData['area_name'],
                    'branch_id' => $branch->id,
                ],
                $areaData
            );
        }

        $this->command->info("    Created areas for branch: {$branch->name}");
    }

    /**
     * Create tables with QR codes for a branch
     */
    private function createTables(Branch $branch): void
    {
        $areas = Area::where('branch_id', $branch->id)->get();
        
        if ($areas->isEmpty()) {
            $this->command->warn("    No areas found for branch: {$branch->name}. Tables cannot be created.");
            return;
        }

        // Create 10-15 tables per branch
        $tableCount = rand(10, 15);
        
        for ($i = 1; $i <= $tableCount; $i++) {
            $area = $areas->random();
            $tableCode = 'T-' . str_pad($i, 2, '0', STR_PAD_LEFT);

            Table::withoutEvents(function () use ($branch, $area, $tableCode) {
                $table = Table::firstOrCreate(
                    [
                        'table_code' => $tableCode,
                        'branch_id' => $branch->id,
                    ],
                    [
                        'table_code' => $tableCode,
                        'area_id' => $area->id,
                        'seating_capacity' => rand(2, 8),
                        'hash' => md5(microtime() . rand(1, 99999999) . $tableCode),
                        'branch_id' => $branch->id,
                    ]
                );

                // Generate QR code if GD extension is available
                try {
                    if (extension_loaded('gd')) {
                        $table->generateQrCode();
                    }
                } catch (\Exception $e) {
                    // Silently skip QR generation if GD not available
                }
            });
        }

        $this->command->info("    Created {$tableCount} tables for branch: {$branch->name}");
    }

    /**
     * Create staff for a branch
     */
    private function createStaff(Branch $branch, Restaurant $restaurant): void
    {
        // Create waiter
        $waiterEmail = 'waiter' . $branch->id . '@' . str_replace(['http://', 'https://', 'www.'], '', parse_url($restaurant->email, PHP_URL_HOST) ?? str_replace('@', '', $restaurant->email));
        if (!filter_var($waiterEmail, FILTER_VALIDATE_EMAIL)) {
            $domain = str_replace(['@', '.'], ['_', '_'], $restaurant->email);
            $waiterEmail = 'waiter' . $branch->id . '@' . $domain . '.demo';
        }

        $waiter = User::firstOrCreate(
            [
                'email' => $waiterEmail,
                'restaurant_id' => $restaurant->id,
            ],
            [
                'name' => fake()->name(),
                'email' => $waiterEmail,
                'password' => bcrypt('123456'),
                'restaurant_id' => $restaurant->id,
                'branch_id' => $branch->id,
            ]
        );

        $waiterRole = Role::where('name', 'Waiter_' . $restaurant->id)->first();
        if ($waiterRole && !$waiter->hasRole($waiterRole)) {
            $waiter->assignRole($waiterRole);
        }

        // Create branch head
        $branchHeadEmail = 'branchhead' . $branch->id . '@' . str_replace(['http://', 'https://', 'www.'], '', parse_url($restaurant->email, PHP_URL_HOST) ?? str_replace('@', '', $restaurant->email));
        if (!filter_var($branchHeadEmail, FILTER_VALIDATE_EMAIL)) {
            $domain = str_replace(['@', '.'], ['_', '_'], $restaurant->email);
            $branchHeadEmail = 'branchhead' . $branch->id . '@' . $domain . '.demo';
        }

        $branchHead = User::firstOrCreate(
            [
                'email' => $branchHeadEmail,
                'restaurant_id' => $restaurant->id,
            ],
            [
                'name' => fake()->name(),
                'email' => $branchHeadEmail,
                'password' => bcrypt('123456'),
                'restaurant_id' => $restaurant->id,
                'branch_id' => $branch->id,
            ]
        );

        $branchHeadRole = Role::where('name', 'Branch Head_' . $restaurant->id)->first();
        if ($branchHeadRole && !$branchHead->hasRole($branchHeadRole)) {
            $branchHead->assignRole($branchHeadRole);
        }

        // Create chef
        $chefEmail = 'chef' . $branch->id . '@' . str_replace(['http://', 'https://', 'www.'], '', parse_url($restaurant->email, PHP_URL_HOST) ?? str_replace('@', '', $restaurant->email));
        if (!filter_var($chefEmail, FILTER_VALIDATE_EMAIL)) {
            $domain = str_replace(['@', '.'], ['_', '_'], $restaurant->email);
            $chefEmail = 'chef' . $branch->id . '@' . $domain . '.demo';
        }

        $chef = User::firstOrCreate(
            [
                'email' => $chefEmail,
                'restaurant_id' => $restaurant->id,
            ],
            [
                'name' => fake()->name(),
                'email' => $chefEmail,
                'password' => bcrypt('123456'),
                'restaurant_id' => $restaurant->id,
                'branch_id' => $branch->id,
            ]
        );

        $chefRole = Role::where('name', 'Chef_' . $restaurant->id)->first();
        if ($chefRole && !$chef->hasRole($chefRole)) {
            $chef->assignRole($chefRole);
        }

        $this->command->info("    Created staff for branch: {$branch->name} (Waiter, Branch Head, Chef)");
    }

    /**
     * Create delivery executives for a branch
     */
    private function createDeliveryExecutives(Branch $branch): void
    {
        // Create 3-5 delivery executives per branch
        $executiveCount = rand(3, 5);

        for ($i = 1; $i <= $executiveCount; $i++) {
            DeliveryExecutive::firstOrCreate(
                [
                    'name' => fake()->name(),
                    'branch_id' => $branch->id,
                ],
                [
                    'name' => fake()->name(),
                    'branch_id' => $branch->id,
                    'phone' => fake()->phoneNumber(),
                    'phone_code' => '+60', // Malaysia phone code
                ]
            );
        }

        $this->command->info("    Created {$executiveCount} delivery executives for branch: {$branch->name}");
    }

    /**
     * Create KOT settings for a branch
     */
    private function createKotSettings(Branch $branch): void
    {
        try {
            // Check if KOT setting already exists
            $kotSetting = \App\Models\KotSetting::where('branch_id', $branch->id)->first();
            
            if (!$kotSetting) {
                $branch->generateKotSetting();
            }
        } catch (\Exception $e) {
            // Silently skip if KOT setting creation fails
            // This prevents seeder from failing if there are any issues
        }
    }
}

