<?php

namespace App\Modules\Stock;

use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Http\Controllers\BaseController;

class StockTransactionControllerRESTv1 extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        $query = StockTransaction::select('*')->with('stock');

        if ($request->has('stock_id')) {
            $query->where('stock_id', $request->input('stock_id'));
        }

        if ($request->has('related_type')) {
            $query->where('related_type', $request->input('related_type'));
        }

        $query = $query->orderBy('id', 'desc');

        // Apply limits and execute the query
        $query = $query->paginate(request()->get('limit', 20));

        $response = [
            'success'      => true,
            'data'         => $query->getCollection()->toArray(),
            'current_page' => $query->currentPage(),
            'last_page'    => $query->lastPage(),
            'from'         => $query->firstItem(),
            'to'           => $query->lastItem(),
        ];

        return response()->json($response);
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store(Request $request)
    {
        $data = $request->all();

        return DB::transaction(function () use ($data) {

            $transaction = StockTransaction::create($data);

            if (! $transaction->id) {
                DB::rollback();

                return response()->json(['error' => $transaction->errors->all()], 404);
            }

            return response()->json($transaction);
        });
    }

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

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

    /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     *
     * @return Response
     */
    public function update($id)
    {
    }

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