<?php

namespace Database\Seeders;

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

class TenantProductSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // Get the first tenant to set up the tenant database connection
        $tenant = \App\Models\Tenant::first();
        
        if (!$tenant) {
            $this->command->error('No tenant found. Please create a tenant first.');
            return;
        }

        // Configure the tenant database connection
        Config::set('database.connections.tenant.database', $tenant->database_name);
        DB::purge('tenant');
        DB::reconnect('tenant');
        
        // Test the connection
        try {
            DB::connection('tenant')->getPdo();
        } catch (\Exception $e) {
            $this->command->error('Cannot connect to tenant database: ' . $e->getMessage());
            return;
        }

        // Create Categories
        $categories = [
            ['name' => 'Beverages', 'created_at' => now(), 'updated_at' => now()],
            ['name' => 'Food Items', 'created_at' => now(), 'updated_at' => now()],
            ['name' => 'Dairy Products', 'created_at' => now(), 'updated_at' => now()],
            ['name' => 'Snacks', 'created_at' => now(), 'updated_at' => now()],
        ];

        foreach ($categories as $category) {
            DB::connection('tenant')->table('categories')->updateOrInsert(
                ['name' => $category['name']],
                $category
            );
        }

        // Get category IDs
        $beverageCat = DB::connection('tenant')->table('categories')->where('name', 'Beverages')->first();
        $foodCat = DB::connection('tenant')->table('categories')->where('name', 'Food Items')->first();
        $dairyCat = DB::connection('tenant')->table('categories')->where('name', 'Dairy Products')->first();
        $snacksCat = DB::connection('tenant')->table('categories')->where('name', 'Snacks')->first();

        // Create Units
        $units = [
            ['name' => 'Piece', 'short_name' => 'pc', 'created_at' => now(), 'updated_at' => now()],
            ['name' => 'Kilogram', 'short_name' => 'kg', 'created_at' => now(), 'updated_at' => now()],
            ['name' => 'Liter', 'short_name' => 'L', 'created_at' => now(), 'updated_at' => now()],
            ['name' => 'Box', 'short_name' => 'box', 'created_at' => now(), 'updated_at' => now()],
        ];

        foreach ($units as $unit) {
            DB::connection('tenant')->table('units')->updateOrInsert(
                ['name' => $unit['name']],
                $unit
            );
        }

        // Get unit IDs
        $pieceUnit = DB::connection('tenant')->table('units')->where('name', 'Piece')->first();
        $kgUnit = DB::connection('tenant')->table('units')->where('name', 'Kilogram')->first();
        $literUnit = DB::connection('tenant')->table('units')->where('name', 'Liter')->first();
        $boxUnit = DB::connection('tenant')->table('units')->where('name', 'Box')->first();

        // Create Products with Variants
        $products = [
            [
                'name' => 'Soft Drink',
                'category_id' => $beverageCat->id,
                'unit_id' => $pieceUnit->id,
                'image' => null,
                'variants' => [
                    ['name' => 'Coca Cola 500ml', 'sku' => 'CC500', 'barcode' => '1234567890', 'price' => 1.50, 'stock' => 50],
                    ['name' => 'Coca Cola 1L', 'sku' => 'CC1000', 'barcode' => '1234567891', 'price' => 2.50, 'stock' => 30],
                    ['name' => 'Pepsi 500ml', 'sku' => 'PEP500', 'barcode' => '1234567892', 'price' => 1.45, 'stock' => 45],
                ]
            ],
            [
                'name' => 'Bread',
                'category_id' => $foodCat->id,
                'unit_id' => $pieceUnit->id,
                'image' => null,
                'variants' => [
                    ['name' => 'White Bread', 'sku' => 'WB001', 'barcode' => '2345678901', 'price' => 2.00, 'stock' => 25],
                    ['name' => 'Whole Wheat Bread', 'sku' => 'WWB001', 'barcode' => '2345678902', 'price' => 2.50, 'stock' => 20],
                ]
            ],
            [
                'name' => 'Milk',
                'category_id' => $dairyCat->id,
                'unit_id' => $literUnit->id,
                'image' => null,
                'variants' => [
                    ['name' => 'Fresh Milk 1L', 'sku' => 'FM1L', 'barcode' => '3456789012', 'price' => 3.50, 'stock' => 40],
                    ['name' => 'Fresh Milk 2L', 'sku' => 'FM2L', 'barcode' => '3456789013', 'price' => 6.50, 'stock' => 20],
                ]
            ],
            [
                'name' => 'Potato Chips',
                'category_id' => $snacksCat->id,
                'unit_id' => $pieceUnit->id,
                'image' => null,
                'variants' => [
                    ['name' => 'Classic Salted 50g', 'sku' => 'PCS50', 'barcode' => '4567890123', 'price' => 1.25, 'stock' => 60],
                    ['name' => 'BBQ Flavor 50g', 'sku' => 'PCB50', 'barcode' => '4567890124', 'price' => 1.35, 'stock' => 55],
                    ['name' => 'Sour Cream 50g', 'sku' => 'PCS50', 'barcode' => '4567890125', 'price' => 1.30, 'stock' => 50],
                ]
            ],
            [
                'name' => 'Rice',
                'category_id' => $foodCat->id,
                'unit_id' => $kgUnit->id,
                'image' => null,
                'variants' => [
                    ['name' => 'Basmati Rice Premium', 'sku' => 'BRP5', 'barcode' => '5678901234', 'price' => 8.00, 'stock' => 100],
                    ['name' => 'Basmati Rice Regular', 'sku' => 'BRR5', 'barcode' => '5678901235', 'price' => 6.50, 'stock' => 80],
                ]
            ],
        ];

        foreach ($products as $productData) {
            $variants = $productData['variants'];
            unset($productData['variants']);
            $productData['created_at'] = now();
            $productData['updated_at'] = now();

            // Insert product
            $productId = DB::connection('tenant')->table('products')->insertGetId($productData);

            // Insert variants
            foreach ($variants as $variant) {
                $variant['product_id'] = $productId;
                $variant['created_at'] = now();
                $variant['updated_at'] = now();
                DB::connection('tenant')->table('product_variants')->insert($variant);
            }
        }

        // Create some demo customers
        $customers = [
            ['name' => 'John Doe', 'phone' => '01234567890', 'address' => '123 Main St', 'is_sub_dealer' => false, 'created_at' => now(), 'updated_at' => now()],
            ['name' => 'Jane Smith', 'phone' => '01334567890', 'address' => '456 Oak Ave', 'is_sub_dealer' => false, 'created_at' => now(), 'updated_at' => now()],
            ['name' => 'ABC Store', 'phone' => '01434567890', 'address' => '789 Market St', 'is_sub_dealer' => true, 'created_at' => now(), 'updated_at' => now()],
        ];

        foreach ($customers as $customer) {
            DB::connection('tenant')->table('customers')->updateOrInsert(
                ['phone' => $customer['phone']],
                $customer
            );
        }

        $this->command->info('Tenant products, categories, units, and customers seeded successfully!');
    }
}
