<?php

use App\Models\Tenant\Product;
use App\Models\Tenant\Unit;
use App\Models\Tenant\Category;
use App\Models\Tenant\Brand;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Config;

// Force Tenant Connection
Config::set('database.connections.tenant.database', 'tenant_demo_grocery');
DB::purge('tenant');
DB::setDefaultConnection('tenant');

// Mock Request Data
$data = [
    'name' => 'Test Pepsi ' . uniqid(),
    'category_id' => Category::first()->id ?? null,
    'brand_id' => Brand::first()->id ?? null,
    'unit_id' => Unit::first()->id ?? null, // Base Unit
    'has_variants' => true,
    
    // Custom Units
    'product_units' => [
        ['name' => 'Case', 'conversion_factor' => 24, 'is_sale' => 'on'],
        ['name' => 'Pack', 'conversion_factor' => 6, 'is_sale' => 'on'],
    ],
    
    // Variants
    'variants' => [
        [
            'sku' => 'PEP-CAN-250-' . uniqid(),
            'stock' => 100,
            'attributes' => [
                ['name' => 'Type', 'value' => 'Can'],
                ['name' => 'Size', 'value' => '250ml']
            ],
            'prices' => [
                ['unit_name' => 'Base Unit', 'price' => 0.50, 'cost' => 0.30], // The tricky one
                ['unit_name' => 'Case', 'price' => 10.00, 'cost' => 7.00],
                ['unit_name' => 'Pack', 'price' => 2.50, 'cost' => 1.80],
            ]
        ]
    ]
];

echo "Simulating Product Creation...\n";

try {
    DB::beginTransaction();
    
    $validator = Validator::make($data, [
        'name' => 'required|string|max:255',
        'unit_id' => 'required|exists:tenant.units,id',
        'has_variants' => 'boolean',
        'product_units' => 'nullable|array',
        'variants' => 'required_if:has_variants,true|array',
    ]);
    
    if ($validator->fails()) {
        throw new Exception("Validation Failed: " . json_encode($validator->errors()->all()));
    }
    
    $validated = $validator->validated();
    
    // 2. Create Product
    $product = Product::create([
        'name' => $validated['name'],
        'category_id' => $validated['category_id'] ?? null,
        'brand_id' => $validated['brand_id'] ?? null,
        'unit_id' => $validated['unit_id'],
        'has_variants' => $validated['has_variants'] ?? false,
    ]);
    
    echo "Product Created: {$product->name} (ID: {$product->id})\n";
    
    // 3. Create Custom Units AND Base Unit Wrapper
    $unitMap = [];
    
    // A. Create Base Unit Wrapper
    $baseUnitGlobal = Unit::find($validated['unit_id']);
    $baseUnitWrapper = $product->productUnits()->create([
        'name' => $baseUnitGlobal->name, // e.g., Piece
        'conversion_factor' => 1,
        'is_base' => true,
        'is_purchase' => true,
        'is_sale' => true,
    ]);
    $unitMap['Base Unit'] = $baseUnitWrapper->id; // Map 'Base Unit' keyword
    $unitMap[$baseUnitGlobal->name] = $baseUnitWrapper->id; // Map actual name
    echo " - Base Unit Wrapper Created: {$baseUnitGlobal->name}\n";

    // B. Create Custom Units
    if (isset($data['product_units'])) {
        foreach ($data['product_units'] as $pUnit) {
            $createdUnit = $product->productUnits()->create([
                'name' => $pUnit['name'],
                'conversion_factor' => $pUnit['conversion_factor'],
                'is_base' => false,
                'is_purchase' => true,
                'is_sale' => isset($pUnit['is_sale']),
            ]);
            $unitMap[$pUnit['name']] = $createdUnit->id;
            echo " - Unit Created: {$pUnit['name']}\n";
        }
    }
    
    // 4. Create Variants
    if ($product->has_variants) {
        foreach ($data['variants'] as $variantData) {
            $variant = $product->variants()->create([
                'name' => $product->name,
                'sku' => $variantData['sku'],
                'stock' => $variantData['stock'] ?? 0,
                'is_active' => true,
            ]);
            echo " - Variant Created: {$variant->sku}\n";
            
            // Attributes
            foreach ($variantData['attributes'] as $attr) {
                $variant->attributes()->create([
                    'name' => $attr['name'],
                    'value' => $attr['value'],
                ]);
            }
            
            // Prices
            foreach ($variantData['prices'] as $priceData) {
                $unitId = null;
                // Try to find by name
                if (isset($unitMap[$priceData['unit_name']])) {
                    $unitId = $unitMap[$priceData['unit_name']];
                }
                
                if ($unitId) {
                    $variant->prices()->create([
                        'product_unit_id' => $unitId,
                        'price' => $priceData['price'],
                        'cost' => $priceData['cost'],
                    ]);
                    echo "   - Price set for {$priceData['unit_name']}: {$priceData['price']}\n";
                } else {
                    echo "   [ERROR] Unit ID not found for {$priceData['unit_name']}\n";
                }
            }
        }
    }
    
    DB::rollBack();
    echo "Test Completed Successfully (Rolled back)\n";
    
} catch (Exception $e) {
    DB::rollBack();
    echo "ERROR: " . $e->getMessage() . "\n";
    echo $e->getTraceAsString();
}
