<?php

namespace App\Http\Controllers;

use App\Models\Purchase;
use Illuminate\Http\Request;

class PurchaseController extends Controller
{
    //

    public function member_all_purchases()
    {
        $purchases = Purchase::all();
        return view('purchases.index', compact('purchases'));
    }

    public function member_new_purchase()
    {
        return view('purchases.create');
    }

    public function member_save_purchase(Request $request)
    {
        $request->validate([
           'product' => 'required:integer',
           'quantity' => 'required:integer',
           'costPrice' => 'required',
           'unit' => 'required:string',
           'date' => 'required',
        ]);

        $purchase = new Purchase([
            'product_id' => $request->product,
            'cost_price' => $request->costPrice,
            'quantity' => $request->quantity,
            'amount' => $request->costPrice * $request->quantity,
            'date' => $request->date,
            'created_by' => auth()->user()->id,
            'unit' => $request->unit,
        ]);

        $purchase->save();

        return redirect()->back()->with('success', "Purchase Saved Successfully");
    }

    public function member_remove_purchase(Purchase $purchase)
    {
        $purchase->delete();
        return redirect()->route('member_all_purchases');
    }
}
