<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Pembelian;
use App\Models\Stock;

class PembelianController extends Controller
{
    public function index(Request $request)
    {
        $search = $request->input('search');

        $pembelians = Pembelian::when($search, function ($query, $search) {
            return $query->where('nama_supplier', 'like', "%{$search}%")
                ->orWhere('nama_barang', 'like', "%{$search}%");
        })->get();

        $stocks = Stock::all();

        return view('pembelian.index', [
            'title' => 'Pembelian',
            'pembelians' => $pembelians,
            'stocks' => $stocks
        ]);
    }

    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'nama_supplier' => 'required|max:255',
            'nama_barang' => 'required|max:255',
            'jumlah_barang' => 'required|integer',
            'harga_barang' => 'required|numeric'
        ]);

        // Hitung harga total
        $validatedData['harga_total'] = $request->jumlah_barang * $request->harga_barang;

        // Simpan pembelian
        $pembelian = Pembelian::create($validatedData);

        // Hitung harga rata-rata dan simpan ke pembelian
        $totalPembelian = Pembelian::where('nama_barang', $request->nama_barang)
            ->where('id', '<=', $pembelian->id)
            ->sum('harga_total');
        $totalJumlahBarang = Pembelian::where('nama_barang', $request->nama_barang)
            ->where('id', '<=', $pembelian->id)
            ->sum('jumlah_barang');
        $averagePrice = $totalPembelian / $totalJumlahBarang;
        $pembelian->harga_average = $averagePrice;
        $pembelian->save();

        // Update atau buat entri stok
        $stock = Stock::firstOrCreate(['nama_barang' => $request->nama_barang]);
        $stock->jumlah_barang += $request->jumlah_barang;
        $stock->harga_average = $averagePrice;
        $stock->save();

        return redirect()->route('pembelian.index')->with('success', 'Pembelian added successfully.');
    }

    public function update(Request $request, Pembelian $pembelian)
    {
        $validatedData = $request->validate([
            'nama_supplier' => 'required|max:255',
            'nama_barang' => 'required|max:255',
            'jumlah_barang' => 'required|integer',
            'harga_barang' => 'required|numeric',
        ]);

        // Calculate harga_total
        $validatedData['harga_total'] = $request->jumlah_barang * $request->harga_barang;

        // Update pembelian
        $pembelian->update($validatedData);

        // Update stock for the new pembelian
        $stock = Stock::firstOrCreate(['nama_barang' => $request->nama_barang]);
        $stock->jumlah_barang += $request->jumlah_barang;
        $stock->save();

        // Recalculate average price
        $totalPembelian = Pembelian::where('nama_barang', $request->nama_barang)
            ->where('id', '<=', $pembelian->id)
            ->sum('harga_total');
        $totalJumlahBarang = Pembelian::where('nama_barang', $request->nama_barang)
            ->where('id', '<=', $pembelian->id)
            ->sum('jumlah_barang');
        $averagePrice = $totalPembelian / $totalJumlahBarang;

        // Update average price in pembelian
        $pembelian->harga_average = $averagePrice;
        $pembelian->save();

        // Update average price in stock
        $stock->harga_average = $averagePrice;
        $stock->save();

        return redirect()->route('pembelian.index')->with('success', 'Pembelian updated successfully.');
    }

    public function destroy(Pembelian $pembelian)
    {
        $stock = Stock::where('nama_barang', $pembelian->nama_barang)->first();
        if ($stock) {
            $stock->jumlah_barang -= $pembelian->jumlah_barang;
            $stock->save();
        }
        $pembelian->delete();
        return redirect()->route('pembelian.index')->with('success', 'Pembelian deleted successfully.');
    }
}
