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

use App\Models\ProductRecipe;
use App\Models\Stock;
use App\Models\Branch;

$branches = Branch::all();
$recipes  = ProductRecipe::with(['product.recipes.rawMaterial'])->get();
$done     = [];

foreach ($recipes as $r) {
    $pid = $r->product_id;
    if (in_array($pid, $done)) continue;
    $done[] = $pid;

    $product = $r->product;
    if (!$product) continue;

    $minStock = null;
    foreach ($product->recipes as $pr) {
        $rm = $pr->rawMaterial;
        if (!$rm || $pr->quantity_needed <= 0) continue;
        $possible = floor($rm->stock_quantity / $pr->quantity_needed);
        if ($minStock === null || $possible < $minStock) {
            $minStock = $possible;
        }
    }

    if ($minStock !== null) {
        foreach ($branches as $b) {
            $stock = Stock::firstOrCreate(
                ['product_id' => $product->id, 'branch' => $b->name],
                ['quantity' => 0, 'unit' => 'Pcs']
            );
            $stock->quantity = $minStock;
            $stock->save();
        }
        echo "✅ {$product->name}: stok = {$minStock} Pcs\n";
    }
}
echo "Selesai!\n";
