<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Stock;
class StockController extends Controller
{
    public function index(Request $request)
    {
        $search = $request->query('search');

        $query = Stock::query();

        // If search query is present, filter stocks based on nama_barang
        if ($search) {
            $query->where('nama_barang', 'like', '%' . $search . '%');
        }

        // Get the stocks with related pembelians
        $stocks = $query->with('pembelians')->get();

        // Calculate average price for each stock
        foreach ($stocks as $stock) {
            $totalPrice = $stock->pembelians->sum('harga_total');
            $totalQuantity = $stock->pembelians->sum('jumlah_barang');
            $averagePrice = $totalPrice / ($totalQuantity != 0 ? $totalQuantity : 1); // Avoid division by zero
            $stock->harga_average = $averagePrice;

            // Save the updated average price to the database
            $stock->save();
        }

        return view('stock.index', [
            'title' => 'Stock',
            'active' => 'stock',
            'stocks' => $stocks,
            'search' => $search,
        ]);
    }

    // Store a newly created stock item in storage
    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'nama_barang' => 'required|max:255',
            'jumlah_barang' => 'required',
        ]);

        Stock::create($validatedData);
        return redirect()->route('stocks.index')->with('success', 'Stock added successfully');
    }

    // Update the specified stock item in storage
    public function update(Request $request, Stock $stock)
    {
        $validatedData = $request->validate([
            'nama_barang' => 'required|max:255',
            'jumlah_barang' => 'required|integer',
        ]);

        $stock->update($validatedData);
        return redirect()->route('stocks.index');
    }

    // Remove the specified stock item from storage
    public function destroy(Stock $stock)
    {
        $stock->delete();
        return redirect()->route('stocks.index');
    }
}
