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

// Fix purchase records
echo "Fixing purchase records...\n";

// Purchase ID 8 - Gula
$purchase8 = \App\Models\Purchase::find(8);
$purchase8->type = 'raw_material';
$purchase8->raw_material_id = 2; // Gula
$purchase8->save();
echo "Purchase 8 (Gula) updated to raw_material type\n";

// Purchase ID 9 - Es Batu
$purchase9 = \App\Models\Purchase::find(9);
$purchase9->type = 'raw_material';
$purchase9->raw_material_id = 3; // Es Batu
$purchase9->save();
echo "Purchase 9 (Es Batu) updated to raw_material type\n";

// Purchase ID 10 - Teh Kotak
$purchase10 = \App\Models\Purchase::find(10);
$purchase10->type = 'raw_material';
$purchase10->raw_material_id = 4; // Teh Kotak
$purchase10->save();
echo "Purchase 10 (Teh Kotak) updated to raw_material type\n";

// Update raw material stocks
echo "\nUpdating raw material stocks...\n";

// Gula: add 1000 Gram
$gula = \App\Models\RawMaterial::find(2);
$gula->stock_quantity += 1000;
$gula->save();
echo "Gula stock updated: " . $gula->stock_quantity . " Gram\n";

// Es Batu: add 1000 Gram
$esBatu = \App\Models\RawMaterial::find(3);
$esBatu->stock_quantity += 1000;
$esBatu->save();
echo "Es Batu stock updated: " . $esBatu->stock_quantity . " Gram\n";

// Teh Kotak: add 10 Pcs
$tehKotak = \App\Models\RawMaterial::find(4);
$tehKotak->stock_quantity += 10;
$tehKotak->save();
echo "Teh Kotak stock updated: " . $tehKotak->stock_quantity . " Pcs\n";

// Recalculate es teh stock
echo "\nRecalculating es teh stock...\n";
$product = \App\Models\Product::with('recipes.rawMaterial')->find(7);
$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);
    echo $rm->name . ": " . $rm->stock_quantity . " / " . $recipe->quantity_needed . " = " . $possibleAmount . " porsi\n";
    if ($minStock === null || $possibleAmount < $minStock) {
        $minStock = $possibleAmount;
    }
}

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

echo "\nDone!\n";
