<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\History;
use App\Models\MasterProduct;
use App\Models\Outbound;
use App\Models\WarehouseStock;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class OutboundController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = Outbound::with('product','warehouse')->get();
        return response()->json($data);
    }

    /**
     * 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)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

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

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $outQty = -$request['out_qty'];
        $item = WarehouseStock::findOrFail($id);
        $math = $item['qty'] - $request['out_qty'];
        $item2 = MasterProduct::findOrFail($item['product_id']);
        try {
            $item->update([
                'qty' => $math
            ]);
            Outbound::create([
                'product_id' => $item['product_id'],
                'warehouse_id' => $item['id'],
                'out_qty' => $outQty,
            ]);
            History::create([
                'product_id' => $item['product_id'],
                'warehouse_id' => $item['id'],
                'update_qty' => $outQty,
                'deskripsi' => $request['deskripsi'],
                'created_by' => $request['created_by']
            ]);
            return ['result'=>$item, $item2];
        } catch (Exception $err) {
            Log::error($err);
            return ['result'=>$err];
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
