<?php

namespace App\Modules\Stock;

use Illuminate\Support\Facades\Config;
use App\Modules\Bookings\Part;
use Illuminate\Http\Request;
use App\Http\Controllers\BaseController;

class HelpersControllerREST extends BaseController
{
    public function postNonStockPart(Request $request)
    {
        $part_type = $request->input('type', 'non_stock');

        // Calculate the cost, in case it includes VAT
        if ($request->input('include_vat', true) && $request->has('cost')) {
            $retail = $request->input('cost');
            $cost = $retail / (Config::get('settings.vat') / 100 + 1);
        } else {
            $cost = $request->input('cost', 0);
            $retail = $cost * (Config::get('settings.vat') / 100 + 1);
        }

        $stock = Stock::query()->where('name', 'like', $request->input('name'))->first();

        if (! $stock) {
            $stock = Stock::create([
                'manufacturer_code' => mt_rand(100000000, mt_getrandmax()),
                'name'              => $request->input('name'),
                'type'              => $part_type,
                'margin'            => 0,
                'business_margin'   => 0,
                'cost'              => $cost,
                'quantity'          => $request->input('quantity', -1),
                'order_id'          => $request->input('order_task_id'),
                'retail'            => $retail,
            ]);
        }

        if ($stock->id) {
            // Add it to parts
            $part = Part::create([
                'related_id'     => $request->input('related_id'),
                'related_type'   => $request->input('related_type'),
                'stock_id'       => $stock->id,
                'quantity'       => $request->input('quantity', 1),
                'price'          => $cost,
                'vat'            => 20,
                'on_order'       => true,

            ]);

            if (! $part->id) {
                return response()->json(['errors' => $part->errors->toArray()], 400);
            } else {
                $part->load('stock', 'stock.order', 'stock.order.status');

                return response()->json($part->toArray());
            }
        } else {
            return response()->json(['errors' => $stock->errors->all()], 400);
        }
    }
}
