isEmpty() || $products->isEmpty()) { return; } // Generate purchases for the last 6 months, twice a month for ($i = 0; $i < 6; $i++) { $monthDate = now()->subMonths($i); // Two purchases per month for ($j = 0; $j < 2; $j++) { $purchase = Purchase::factory()->create([ 'created_at' => $monthDate->copy()->startOfMonth()->addDays(rand(0, 28))->setTime(rand(8, 17), rand(0, 59)), ]); $itemsCount = rand(1, 5); $total = 0; for ($k = 0; $k < $itemsCount; $k++) { $product = $products->random(); $quantity = rand(1, 10); $unitPrice = rand(10000, 500000); $totalPrice = $quantity * $unitPrice; PurchaseItem::create([ 'purchase_id' => $purchase->id, 'user_id' => $users->random()->id, 'product_id' => $product->id, 'quantity' => $quantity, 'unit_price' => $unitPrice, 'total_price' => $totalPrice, 'created_at' => $purchase->created_at, ]); $product->increment('stock', $quantity); $total += $totalPrice; } $purchase->update(['total' => $total]); } } } }