<?php

namespace Database\Seeders;

use App\Models\Brand;
use App\Models\Category;
use App\Models\Customer;
use App\Models\FinancialYear;
use App\Models\Permission;
use App\Models\Product;
use App\Models\ProductUnit;
use App\Models\ProductBarcode;
use App\Models\Supplier;
use App\Models\TranslationDictionary;
use App\Models\Unit;
use App\Models\User;
use App\Models\Warehouse;
use App\Models\WarehouseStock;
use App\Models\StockLedger;
use Illuminate\Database\Seeder;

class Prompt2Seeder extends Seeder
{
    public function run(): void
    {
        $creatorId = User::where('username', 'admin')->value('id');

        // ============================================================
        // 1. UNITS
        // ============================================================
        $unitsData = [
            ['code' => 'PCS',  'name_en' => 'Piece',      'name_ar' => 'قطعة',    'short_name_en' => 'Pcs',  'short_name_ar' => 'قطعة',  'allow_decimal' => false],
            ['code' => 'CTN',  'name_en' => 'Carton',     'name_ar' => 'كرتون',   'short_name_en' => 'Ctn',  'short_name_ar' => 'كرتون', 'allow_decimal' => false],
            ['code' => 'BOX',  'name_en' => 'Box',        'name_ar' => 'صندوق',   'short_name_en' => 'Box',  'short_name_ar' => 'صندوق', 'allow_decimal' => false],
            ['code' => 'PKT',  'name_en' => 'Packet',     'name_ar' => 'باكيت',   'short_name_en' => 'Pkt',  'short_name_ar' => 'باكيت', 'allow_decimal' => false],
            ['code' => 'KG',   'name_en' => 'Kilogram',   'name_ar' => 'كجم',     'short_name_en' => 'Kg',   'short_name_ar' => 'كجم',   'allow_decimal' => true],
            ['code' => 'GM',   'name_en' => 'Gram',       'name_ar' => 'جرام',    'short_name_en' => 'Gm',   'short_name_ar' => 'جرام',  'allow_decimal' => true],
            ['code' => 'LTR',  'name_en' => 'Liter',      'name_ar' => 'لتر',     'short_name_en' => 'Ltr',  'short_name_ar' => 'لتر',   'allow_decimal' => true],
            ['code' => 'ML',   'name_en' => 'Millilitre', 'name_ar' => 'مل',      'short_name_en' => 'Ml',   'short_name_ar' => 'مل',    'allow_decimal' => true],
            ['code' => 'DOZ',  'name_en' => 'Dozen',      'name_ar' => 'درزن',    'short_name_en' => 'Doz',  'short_name_ar' => 'درزن',  'allow_decimal' => false],
        ];

        foreach ($unitsData as $unit) {
            Unit::firstOrCreate(['code' => $unit['code']], $unit);
        }

        $pcs = Unit::where('code', 'PCS')->first();
        $ctn = Unit::where('code', 'CTN')->first();

        // ============================================================
        // 2. BRANDS
        // ============================================================
        $brandsData = [
            ['code' => 'MIRINDA',  'name_en' => 'MIRINDA',   'name_ar' => 'ميرندا',     'status' => 'active'],
            ['code' => 'SUNTOP',   'name_en' => 'SUN TOP',   'name_ar' => 'سن توب',     'status' => 'active'],
            ['code' => 'DEW',      'name_en' => 'DEW',       'name_ar' => 'ديو',        'status' => 'active'],
            ['code' => 'BUTAN',    'name_en' => 'BUTAN',     'name_ar' => 'بوتان',      'status' => 'active'],
            ['code' => 'SAUDI',    'name_en' => 'SAUDI',     'name_ar' => 'سعودي',      'status' => 'active'],
            ['code' => 'ALMARAI',  'name_en' => 'ALMARAI',   'name_ar' => 'المراعي',    'status' => 'active'],
            ['code' => 'NADA',     'name_en' => 'NADA',      'name_ar' => 'ندى',        'status' => 'active'],
        ];

        foreach ($brandsData as $brand) {
            Brand::firstOrCreate(['code' => $brand['code']], $brand);
        }

        // ============================================================
        // 3. CATEGORIES
        // ============================================================
        $food = Category::firstOrCreate(['code' => 'FOOD'], [
            'name_en' => 'Food', 'name_ar' => 'غذاء', 'status' => 'active',
        ]);

        $canned = Category::firstOrCreate(['code' => 'CANNED'], [
            'name_en' => 'Canned Food', 'name_ar' => 'الأغذية المعلبة',
            'parent_id' => $food->id, 'status' => 'active',
        ]);

        $beverages = Category::firstOrCreate(['code' => 'BEV'], [
            'name_en' => 'Beverages', 'name_ar' => 'مشروبات',
            'parent_id' => $food->id, 'status' => 'active',
        ]);

        $snacks = Category::firstOrCreate(['code' => 'SNACKS'], [
            'name_en' => 'Snacks', 'name_ar' => 'وجبات خفيفة',
            'parent_id' => $food->id, 'status' => 'active',
        ]);

        // ============================================================
        // 4. TRANSLATION DICTIONARY
        // ============================================================
        $dictTerms = [
            ['english_term' => 'TOMATO PASTE',    'arabic_term' => 'معجون طماطم',    'type' => 'product'],
            ['english_term' => 'TUNA',             'arabic_term' => 'تونا',           'type' => 'product'],
            ['english_term' => 'ORANGE',           'arabic_term' => 'برتقال',         'type' => 'flavour'],
            ['english_term' => 'CITRUS',           'arabic_term' => 'حمضيات',         'type' => 'flavour'],
            ['english_term' => 'BIG',              'arabic_term' => 'كبير',           'type' => 'size'],
            ['english_term' => 'SMALL',            'arabic_term' => 'صغير',           'type' => 'size'],
            ['english_term' => 'FAMILY',           'arabic_term' => 'عائلي',          'type' => 'size'],
            ['english_term' => 'JUMBO',            'arabic_term' => 'جامبو',          'type' => 'size'],
            ['english_term' => 'GM',               'arabic_term' => 'جرام',           'type' => 'unit'],
            ['english_term' => 'ML',               'arabic_term' => 'مل',             'type' => 'unit'],
            ['english_term' => 'LTR',              'arabic_term' => 'لتر',            'type' => 'unit'],
            ['english_term' => 'KG',               'arabic_term' => 'كجم',            'type' => 'unit'],
            ['english_term' => 'CTN',              'arabic_term' => 'كرتون',          'type' => 'unit'],
            ['english_term' => 'PCS',              'arabic_term' => 'قطعة',           'type' => 'unit'],
            ['english_term' => 'BOX',              'arabic_term' => 'صندوق',          'type' => 'unit'],
            ['english_term' => 'PKT',              'arabic_term' => 'باكيت',          'type' => 'unit'],
            ['english_term' => 'SAUDI',            'arabic_term' => 'سعودي',          'type' => 'brand'],
            ['english_term' => 'MIRINDA',          'arabic_term' => 'ميرندا',         'type' => 'brand'],
            ['english_term' => 'SUN TOP',          'arabic_term' => 'سن توب',         'type' => 'brand'],
            ['english_term' => 'DEW',              'arabic_term' => 'ديو',            'type' => 'brand'],
            ['english_term' => 'BUTAN',            'arabic_term' => 'بوتان',          'type' => 'brand'],
            ['english_term' => 'ALMARAI',          'arabic_term' => 'المراعي',        'type' => 'brand'],
        ];

        foreach ($dictTerms as $term) {
            TranslationDictionary::firstOrCreate(
                ['english_term' => $term['english_term']],
                $term
            );
        }

        // ============================================================
        // 5. SAMPLE PRODUCTS (Saudi Wholesale Grocery)
        // ============================================================
        $warehouseMain = Warehouse::where('code', 'WH-001')->first()
            ?? Warehouse::first();

        $saudiCategoryId = $canned->id;

        $productsData = [
            [
                'product_code' => 'PRD-001',
                'barcode'      => '6281234500001',
                'name_en'      => 'TOMATO PASTE SAUDI 135 GM',
                'name_ar'      => 'معجون طماطم سعودي 135 جرام',
                'category_id'  => $canned->id,
                'brand_id'     => Brand::where('code', 'SAUDI')->value('id'),
                'cost_price'   => 55.00,
                'avg_cost'     => 55.00,
                'sale_price'   => 65.00,
                'wholesale_price' => 60.00,
                'vat_rate'     => 15.00,
                'pcs_per_carton' => 48,
                'packing_desc_en' => '48 X 135 GM',
                'packing_desc_ar' => '48 × 135 جرام',
                'base_qty'     => 100 * 48, // 100 CTN = 4800 PCS
                'stock_qty_ctn' => 100,
            ],
            [
                'product_code' => 'PRD-002',
                'barcode'      => '6281234500002',
                'name_en'      => 'TUNA BUTAN SMALL 48 X 90 GM',
                'name_ar'      => 'تونا بوتان صغير 48 × 90 جرام',
                'category_id'  => $canned->id,
                'brand_id'     => Brand::where('code', 'BUTAN')->value('id'),
                'cost_price'   => 80.00,
                'avg_cost'     => 80.00,
                'sale_price'   => 92.00,
                'wholesale_price' => 88.00,
                'vat_rate'     => 15.00,
                'pcs_per_carton' => 48,
                'packing_desc_en' => '48 X 90 GM',
                'packing_desc_ar' => '48 × 90 جرام',
                'base_qty'     => 80 * 48,
                'stock_qty_ctn' => 80,
            ],
            [
                'product_code' => 'PRD-003',
                'barcode'      => '6281234500003',
                'name_en'      => 'SUN TOP ORANGE BIG 30 X 250 ML',
                'name_ar'      => 'سن توب برتقال كبير 30 × 250 مل',
                'category_id'  => $beverages->id,
                'brand_id'     => Brand::where('code', 'SUNTOP')->value('id'),
                'cost_price'   => 45.00,
                'avg_cost'     => 45.00,
                'sale_price'   => 54.00,
                'wholesale_price' => 50.00,
                'vat_rate'     => 15.00,
                'pcs_per_carton' => 30,
                'packing_desc_en' => '30 X 250 ML',
                'packing_desc_ar' => '30 × 250 مل',
                'base_qty'     => 60 * 30,
                'stock_qty_ctn' => 60,
            ],
            [
                'product_code' => 'PRD-004',
                'barcode'      => '6281234500004',
                'name_en'      => 'DEW 24 X 320 ML',
                'name_ar'      => 'ديو 24 × 320 مل',
                'category_id'  => $beverages->id,
                'brand_id'     => Brand::where('code', 'DEW')->value('id'),
                'cost_price'   => 38.00,
                'avg_cost'     => 38.00,
                'sale_price'   => 46.00,
                'wholesale_price' => 42.00,
                'vat_rate'     => 15.00,
                'pcs_per_carton' => 24,
                'packing_desc_en' => '24 X 320 ML',
                'packing_desc_ar' => '24 × 320 مل',
                'base_qty'     => 120 * 24,
                'stock_qty_ctn' => 120,
            ],
            [
                'product_code' => 'PRD-005',
                'barcode'      => '6281234500005',
                'name_en'      => 'MIRINDA CITRUS 24 X 320 ML',
                'name_ar'      => 'ميرندا حمضيات 24 × 320 مل',
                'category_id'  => $beverages->id,
                'brand_id'     => Brand::where('code', 'MIRINDA')->value('id'),
                'cost_price'   => 38.00,
                'avg_cost'     => 38.00,
                'sale_price'   => 46.00,
                'wholesale_price' => 42.00,
                'vat_rate'     => 15.00,
                'pcs_per_carton' => 24,
                'packing_desc_en' => '24 X 320 ML',
                'packing_desc_ar' => '24 × 320 مل',
                'base_qty'     => 90 * 24,
                'stock_qty_ctn' => 90,
            ],
        ];

        foreach ($productsData as $pd) {
            $baseQty  = $pd['base_qty'];
            $stockCtn = $pd['stock_qty_ctn'];

            $product = Product::firstOrCreate(
                ['product_code' => $pd['product_code']],
                [
                    'sku'            => $pd['product_code'],
                    'barcode'        => $pd['barcode'],
                    'name_en'        => $pd['name_en'],
                    'name_ar'        => $pd['name_ar'],
                    'category_id'    => $pd['category_id'],
                    'subcategory_id' => null,
                    'brand_id'       => $pd['brand_id'],
                    'product_type'   => 'stock',
                    'base_unit_id'   => $pcs ? $pcs->id : null,
                    'purchase_unit_id' => $ctn ? $ctn->id : null,
                    'sales_unit_id'  => $ctn ? $ctn->id : null,
                    'pcs_per_carton' => $pd['pcs_per_carton'],
                    'packing_desc_en'=> $pd['packing_desc_en'],
                    'packing_desc_ar'=> $pd['packing_desc_ar'],
                    'vat_applicable' => true,
                    'vat_rate'       => $pd['vat_rate'],
                    'vat_category'   => 'Standard',
                    'cost_price'     => $pd['cost_price'],
                    'avg_cost'       => round($pd['avg_cost'] / $pd['pcs_per_carton'], 4),
                    'last_purchase_cost' => round($pd['cost_price'] / $pd['pcs_per_carton'], 4),
                    'sale_price'     => $pd['sale_price'],
                    'wholesale_price'=> $pd['wholesale_price'],
                    'min_sale_price' => $pd['cost_price'],
                    'retail_price'   => $pd['sale_price'],
                    'price_mode'     => 'Exclusive VAT',
                    'track_stock'    => true,
                    'allow_negative_stock' => false,
                    'reorder_level'  => 10,
                    'reorder_qty'    => 50,
                    'track_batch'    => false,
                    'track_expiry'   => false,
                    'track_serial'   => false,
                    'default_warehouse_id' => $warehouseMain ? $warehouseMain->id : null,
                    'status'         => 'active',
                    'created_by'     => $creatorId,
                ]
            );

            // Create multi-unit rows (PCS base + CTN conversion)
            if ($pcs && !ProductUnit::where('product_id', $product->id)->where('unit_id', $pcs->id)->exists()) {
                ProductUnit::create([
                    'product_id' => $product->id, 'unit_id' => $pcs->id,
                    'conversion_factor' => 1.0, 'is_base_unit' => true,
                    'is_purchase_unit' => false, 'is_sales_unit' => false,
                    'purchase_price' => round($pd['cost_price'] / $pd['pcs_per_carton'], 4),
                    'selling_price'  => round($pd['sale_price'] / $pd['pcs_per_carton'], 4),
                    'wholesale_price'=> round($pd['wholesale_price'] / $pd['pcs_per_carton'], 4),
                ]);
            }

            if ($ctn && !ProductUnit::where('product_id', $product->id)->where('unit_id', $ctn->id)->exists()) {
                ProductUnit::create([
                    'product_id' => $product->id, 'unit_id' => $ctn->id,
                    'conversion_factor' => $pd['pcs_per_carton'],
                    'is_base_unit' => false, 'is_purchase_unit' => true, 'is_sales_unit' => true,
                    'purchase_price' => $pd['cost_price'],
                    'selling_price'  => $pd['sale_price'],
                    'wholesale_price'=> $pd['wholesale_price'],
                ]);
            }

            // Create primary barcode
            if (!ProductBarcode::where('barcode', $pd['barcode'])->exists()) {
                ProductBarcode::create([
                    'product_id'  => $product->id,
                    'unit_id'     => $ctn ? $ctn->id : null,
                    'barcode'     => $pd['barcode'],
                    'barcode_type'=> 'EAN13',
                    'is_primary'  => true,
                ]);
            }

            // Seed warehouse stock for main warehouse
            if ($warehouseMain) {
                WarehouseStock::firstOrCreate(
                    ['product_id' => $product->id, 'warehouse_id' => $warehouseMain->id],
                    ['qty' => $baseQty, 'avg_cost' => round($pd['avg_cost'] / $pd['pcs_per_carton'], 4)]
                );

                // Post stock ledger entry
                if (!StockLedger::where('product_id', $product->id)->where('transaction_type', 'OPENING_STOCK')->exists()) {
                    StockLedger::create([
                        'transaction_date'  => now()->toDateString(),
                        'transaction_type'  => 'OPENING_STOCK',
                        'reference_type'    => 'seed',
                        'reference_number'  => 'SEED-OS-' . $pd['product_code'],
                        'product_id'        => $product->id,
                        'warehouse_id'      => $warehouseMain->id,
                        'unit_id'           => $ctn ? $ctn->id : null,
                        'qty_in'            => $stockCtn,
                        'qty_out'           => 0,
                        'base_qty_in'       => $baseQty,
                        'base_qty_out'      => 0,
                        'unit_cost'         => round($pd['avg_cost'] / $pd['pcs_per_carton'], 4),
                        'total_cost'        => round($stockCtn * $pd['avg_cost'], 4),
                        'running_quantity'  => $baseQty,
                        'financial_year_id' => FinancialYear::first()?->id,
                        'created_by'        => $creatorId,
                    ]);
                }
            }
        }

        // ============================================================
        // 6. DEFAULT CASH CUSTOMER
        // ============================================================
        Customer::firstOrCreate(
            ['customer_code' => 'CASH'],
            [
                'name_en'       => 'CASH CUSTOMER',
                'name_ar'       => 'عميل نقدي',
                'customer_type' => 'cash',
                'price_level'   => 'retail',
                'credit_allowed'=> false,
                'default_payment_type' => 'cash',
                'vat_registered'=> false,
                'is_system'     => true,
                'status'        => 'active',
            ]
        );

        // Sample business customers
        $customers = [
            ['customer_code' => 'CUS-0001', 'name_en' => 'AL NOOR MARKET',    'name_ar' => 'سوق النور',     'mobile' => '0512345678', 'city_en' => 'Jeddah',  'credit_limit' => 20000, 'credit_allowed' => true],
            ['customer_code' => 'CUS-0002', 'name_en' => 'RIYADH WHOLESALE',  'name_ar' => 'الرياض للجملة','mobile' => '0556789012', 'city_en' => 'Riyadh',  'credit_limit' => 50000, 'credit_allowed' => true],
            ['customer_code' => 'CUS-0003', 'name_en' => 'AL BAIK TRADING',   'name_ar' => 'البيك للتجارة', 'mobile' => '0598765432', 'city_en' => 'Makkah',  'credit_limit' => 15000, 'credit_allowed' => false],
        ];

        foreach ($customers as $c) {
            Customer::firstOrCreate(['customer_code' => $c['customer_code']], array_merge($c, [
                'customer_type' => 'business', 'price_level' => 'wholesale',
                'default_payment_type' => 'credit', 'vat_registered' => false, 'status' => 'active',
            ]));
        }

        // ============================================================
        // 7. SAMPLE SUPPLIERS
        // ============================================================
        $suppliers = [
            ['supplier_code' => 'SUP-0001', 'name_en' => 'ABC TRADING EST',     'name_ar' => 'مؤسسة أيه بي سي التجارية', 'mobile' => '0512345001', 'city' => 'Jeddah',  'credit_days' => 30],
            ['supplier_code' => 'SUP-0002', 'name_en' => 'SAUDI FOOD DIST.',    'name_ar' => 'توزيع المواد الغذائية السعودية', 'mobile' => '0512345002', 'city' => 'Riyadh', 'credit_days' => 45],
            ['supplier_code' => 'SUP-0003', 'name_en' => 'GULF BEVERAGES CO.',  'name_ar' => 'شركة مشروبات الخليج',     'mobile' => '0512345003', 'city' => 'Dammam', 'credit_days' => 30],
        ];

        foreach ($suppliers as $s) {
            Supplier::firstOrCreate(['supplier_code' => $s['supplier_code']], array_merge($s, [
                'vat_registered' => false, 'country' => 'Saudi Arabia', 'status' => 'active',
            ]));
        }

        // ============================================================
        // 8. PROMPT 2 PERMISSIONS
        // ============================================================
        $prompt2Permissions = [
            // Product
            'product.view', 'product.create', 'product.edit', 'product.deactivate',
            'product.view_cost', 'product.view_profit', 'product.import', 'product.export', 'product.translate',
            // Category
            'category.view', 'category.create', 'category.edit',
            // Brand
            'brand.view', 'brand.create', 'brand.edit',
            // Customer
            'customer.view', 'customer.create', 'customer.edit',
            'customer.view_statement', 'customer.view_balance',
            // Supplier
            'supplier.view', 'supplier.create', 'supplier.edit',
            'supplier.view_statement', 'supplier.view_balance',
            // Inventory
            'inventory.view', 'inventory.view_cost', 'inventory.opening_stock',
            'inventory.stock_adjustment', 'inventory.stock_transfer',
            'inventory.approve_transfer', 'inventory.receive_transfer',
            'inventory.view_stock_ledger', 'inventory.view_stock_value',
        ];

        foreach ($prompt2Permissions as $perm) {
            [$module, $action] = explode('.', $perm, 2);
            $displayName = ucwords(str_replace(['_', '.'], ' ', $perm));
            Permission::firstOrCreate(
                ['slug' => $perm],
                [
                    'name'   => $displayName,
                    'slug'   => $perm,
                    'module' => $module,
                ]
            );
        }

        $this->command->info('✅ Prompt 2 seeder complete: units, brands, categories, translation dict, 5 products, cash customer, 3 customers, 3 suppliers, permissions.');
    }
}
