<?php
require __DIR__ . '/vendor/autoload.php';
$app = require_once __DIR__ . '/bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$kernel->bootstrap();

// Create product
$product = \App\Models\Product::create([
    'name' => 'es teh',
    'category' => 'minuman',
    'purchase_price' => 4000,
    'selling_price' => 5000,
    'branch' => 'Cabang 2'
]);

echo "Product created with ID: " . $product->id . "\n";

// Create recipes
\App\Models\ProductRecipe::create([
    'product_id' => $product->id,
    'raw_material_id' => 3, // Es Batu
    'quantity_needed' => 15
]);
echo "Recipe added: Es Batu 15 Gram\n";

\App\Models\ProductRecipe::create([
    'product_id' => $product->id,
    'raw_material_id' => 2, // Gula
    'quantity_needed' => 20
]);
echo "Recipe added: Gula 20 Gram\n";

\App\Models\ProductRecipe::create([
    'product_id' => $product->id,
    'raw_material_id' => 4, // Teh Kotak
    'quantity_needed' => 0.5 // 1 pcs untuk 2 es teh
]);
echo "Recipe added: Teh Kotak 0.5 Pcs\n";

// Create initial stock
\App\Models\Stock::create([
    'product_id' => $product->id,
    'branch' => 'Cabang 2',
    'quantity' => 0,
    'unit' => 'Pcs'
]);
echo "Initial stock created\n";

// Recalculate stock
$product = \App\Models\Product::with('recipes.rawMaterial')->find($product->id);
$minStock = null;
foreach ($product->recipes as $recipe) {
    $rm = $recipe->rawMaterial;
    if (!$rm || $recipe->quantity_needed <= 0) continue;
    $possibleAmount = floor($rm->stock_quantity / $recipe->quantity_needed);
    if ($minStock === null || $possibleAmount < $minStock) {
        $minStock = $possibleAmount;
    }
}

if ($minStock !== null && $minStock >= 0) {
    $stock = \App\Models\Stock::where('product_id', $product->id)->where('branch', 'Cabang 2')->first();
    $stock->quantity = $minStock;
    $stock->save();
    echo "Stock recalculated: " . $minStock . " Pcs\n";
} else {
    echo "Stock could not be calculated (insufficient raw materials)\n";
}

echo "Done!\n";
