<?php

namespace App\Console\Commands;

use App\Models\Outlet;
use App\Models\StockOpname;
use App\Models\StockOpnameItem;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class GenerateStockOpname extends Command
{
    protected $signature = 'stock-opname:generate';

    protected $description = 'Automatically generate stock opname documents';

    public function handle()
    {
        $periodMonth = now()->format('Y-m');

        $outlets = Outlet::query()
            ->operational()
            ->with(['perfumes', 'bottles', 'products'])
            ->get();

        $user = User::role('Developer')->first();

        DB::transaction(function () use ($outlets, $periodMonth, $user) {
            foreach ($outlets as $outlet) {
                $stockOpname = StockOpname::firstOrCreate([
                    'outlet_id' => $outlet->id,
                    'period_month' => $periodMonth,
                ]);

                $items = collect()
                    ->merge($outlet->perfumes)
                    ->merge($outlet->bottles)
                    ->merge($outlet->products);

                foreach ($items as $item) {
                    StockOpnameItem::firstOrCreate([
                        'stock_opname_id' => $stockOpname->id,
                        'itemable_type' => get_class($item),
                        'itemable_id' => $item->id,
                    ], [
                        'user_id' => $user->id,
                        'qty_system' => $item->pivot?->stock,
                    ]);
                }
            }
        });

        $this->info("Stock opname untuk bulan {$periodMonth} berhasil digenerate.");
    }
}
