<?php

namespace App\Http\Controllers;

use App\Models\Grn;
use App\Models\GrnHasItem;
use Illuminate\Http\Request;

class GrnHasItemController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request, $grn_id)
    {
        //
        $request->validate([

            'item' => 'required|gt:0',
            'price_buy' => 'required',
            'price_sell' => 'required',
            'qty' => 'required|gt:0',
            'grn' => 'required|gt:0'
        ], [
            'item.gt' => 'The item should be valid'
        ]);


        $grnHasItem = [
            'item_id' => $request->item,
            'price_buy' => $request->price_buy,
            'price_sell' => $request->price_sell,
            'qty' => $request->qty,
            'grn_id' => $request->grn

        ];


        $grnHasItem = GrnHasItem::create($grnHasItem);
        $grnHasItem->code =  "GHI-" . str_pad($grnHasItem->id, 5, '0', STR_PAD_LEFT); // LN-001, LN-002 etc.
        $grnHasItem->save();

        //save stock data

        return redirect('grn/edit/' . $request->grn)->with('success', 'GRN item added successfully');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\GrnHasItem  $grnHasItem
     * @return \Illuminate\Http\Response
     */
    public function show(GrnHasItem $grnHasItem)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\GrnHasItem  $grnHasItem
     * @return \Illuminate\Http\Response
     */
    public function edit(GrnHasItem $grnHasItem)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\GrnHasItem  $grnHasItem
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, GrnHasItem $grnHasItem)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\GrnHasItem  $grnHasItem
     * @return \Illuminate\Http\Response
     */
    public function destroy(GrnHasItem $grnHasItem, $id)
    {
        //
        $grnHasItem =  GrnHasItem::findOrFail($id);
        $grnHasItem->delete();
        return redirect('grn/edit/' . $grnHasItem->grn_id)->with('success', 'GRN item removed successfully');
    }
}
