<?php

namespace App\Modules\Stock;

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

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

        if ($request->has('aknowledged')) {
            $query->where('aknowledged', $request->input('aknowledged') == 'true' ? 1 : 0);
        }

        if ($request->input('type', null) == 'matched') {
            $query->where('old_quantity',  DB::raw('new_quantity'));
        }

        if ($request->input('type', null) == 'mismatched') {
            $query->where('old_quantity', '!=',  DB::raw('new_quantity'));
        }

        // If the request contains a search, use fuzzy search.
        if ($request->input('query')) {
            $query->where('name', 'like', "%" . $request->input('query') . "%");
        }

        $query = $query->paginate($request->input('limit', 20));

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

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

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store(Request $request)
    {
        // Validate required inputs
        $quantity = $request->input('quantity');
        $stock_id = $request->input('stock_id');
        
        if (is_null($quantity)) {
            return response()->json(['success' => false, 'error' => 'Quantity is required'], 400);
        }
        
        if (is_null($stock_id)) {
            return response()->json(['success' => false, 'error' => 'Stock ID is required'], 400);
        }
        
        if ($quantity < 0) {
            throw new \Exception('The quantity in stock can not be lower than 0.', 1);
        }

        $report = DB::transaction(function () use ($request, $quantity, $stock_id) {

            $stock = Stock::findOrFail($stock_id);
            $data = $request->all();
            $data['old_quantity'] = $stock->quantity;
            $data['new_quantity'] = $quantity;
            $report = StockReport::create($data);

            if ($report->exists) {
                Event::dispatch('StockReportCreated', [$report]);
            }

            return $report;
        });

        if ($report->exists) {
            return response()->json(['success' => true, 'data' => $report]);
        }

        return response()->json(['errors'  => $report->errors->all()], 400);
    }

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

    /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     *
     * @return Response
     */
    public function update($id)
    {
        $report = StockReport::findOrFail($id);

        if ($request->has('aknowledged')) {
            $report->update(['aknowledged' => 1]);
        }

        return response()->json(['success' => true, 'data' => $report]);
    }

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