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

use App\Models\Product;
use App\Models\ProductSize;

$inventory = [
    ['name' => 'Kaos Polos Cotton', 'size' => 'M', 'stock' => 25],
    ['name' => 'Kemeja Kerja Putih', 'size' => 'L', 'stock' => 18],
    ['name' => 'Blouse Wanita Floral', 'size' => 'S', 'stock' => 12],
    ['name' => 'Tunik Batik Modern', 'size' => 'M', 'stock' => 10],
    ['name' => 'Tank Top Sporty', 'size' => 'L', 'stock' => 22],
    ['name' => 'Celana Jeans Slim-fit', 'size' => '30', 'stock' => 24],
    ['name' => 'Rok Midi Polos', 'size' => 'M', 'stock' => 16],
    ['name' => 'Celana Chino Pria', 'size' => '32', 'stock' => 14],
    ['name' => 'Legging Olahraga', 'size' => 'S', 'stock' => 33],
    ['name' => 'Shorts Denim', 'size' => 'M', 'stock' => 20],
    ['name' => 'Jaket Bomber Pilot', 'size' => 'XL', 'stock' => 4],
    ['name' => 'Cardigan Premium Rajut', 'size' => 'S', 'stock' => 45],
    ['name' => 'Hoodie Cotton Fleece', 'size' => 'L', 'stock' => 28],
    ['name' => 'Windbreaker Water Resistant', 'size' => 'M', 'stock' => 9],
    ['name' => 'Parka Winter', 'size' => 'XL', 'stock' => 6],
    ['name' => 'Dress Pesta Satin', 'size' => 'M', 'stock' => 7],
    ['name' => 'Mini Dress Polos', 'size' => 'S', 'stock' => 13],
    ['name' => 'Maxi Dress Floral', 'size' => 'L', 'stock' => 11],
    ['name' => 'Dress Midi Batik', 'size' => 'M', 'stock' => 8],
    ['name' => 'Set Olahraga Training', 'size' => 'M', 'stock' => 19],
    ['name' => 'Polo Shirt Golf', 'size' => 'L', 'stock' => 21],
    ['name' => 'Shorts Basketball', 'size' => 'XL', 'stock' => 12],
    ['name' => 'Set Piyama Katun', 'size' => 'M', 'stock' => 17],
    ['name' => 'Loungewear Hoodie', 'size' => 'L', 'stock' => 20],
    ['name' => 'Set Kemeja Tidur', 'size' => 'S', 'stock' => 9],
];

foreach (Product::all() as $product) {
    $sizes = ProductSize::on('sizes_db')->where('product_id', $product->id)->orderBy('id')->get();
    if ($sizes->isEmpty()) {
        echo "No sizes found for {$product->name}\n";
        continue;
    }

    $totalStock = $sizes->sum('stock');
    if ($totalStock <= 0) {
        echo "Skipping {$product->name} because total stock is zero\n";
        continue;
    }

    $sizeCount = $sizes->count();
    $baseStock = intdiv($totalStock, $sizeCount);
    $remainder = $totalStock % $sizeCount;

    foreach ($sizes as $index => $sizeRow) {
        $newStock = $baseStock + ($index < $remainder ? 1 : 0);
        $sizeRow->stock = $newStock;
        $sizeRow->save();
    }

    $product->syncStock();
    echo "Distributed {$totalStock} stock across {$sizeCount} sizes for {$product->name}\n";
}

echo "Restore complete." . PHP_EOL;
