<?php

namespace App\Http\Controllers\api\v1;

use App\Models\api\v1\Stock;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;


class StockController extends Controller
{
    /**
     * this function allows you to create a stock for a space
     * @param Request $request
     * @return JsonResponse
     */
    public function create(Request $request)
    {
        $validator = Validator::make(
            $request->all(),
            [
                'item_id'               => 'required|exists:items,id',
                'space_id'              => 'required|exists:spaces,id',
                'price'                 => 'required|numeric|min:0',
                'off_by_percentage'     => 'required|numeric|min:0|max:100',
                'off_by_number'         => 'required|numeric|min:0',
                "quantity"              => "required|numeric|min:0",
            ]
        );

        //si erreur
        if($validator->fails()){
            return $this->ReturnResponse(false, $validator->errors(), [], 400);
        }

        try {
            //si validé alors connexion
            $stock = null;
            $check = Stock::where([['item_id',$request->item_id],['space_id',$request->space_id],['is_deleted',0]])->first();
            
            
            if(!$check)
            {
                $stock = Stock::create([
                    'item_id'               => $request->item_id,
                    'space_id'              => $request->space_id,
                    'price'                 => $request->price,
                    'off_by_percentage'     => $request->off_by_percentage,
                    'off_by_number'         => $request->off_by_number,
                    "quantity"              => $request->quantity ?? 0,
                    "created_by"            => auth()->user()->id,
                ]);
                return $this->ReturnResponse(true, "Stock créé avec succès", [$stock], 200);
            }else{
                return $this->ReturnResponse(true, "Le produit existe déjà dans cette espace; veuillez faire une mise à jour", [], 406);
            }

            //retour formaté depuis commonController
            
        } catch (Exception $e) {
            $message = "Stock - details - " . $e->getMessage() . " - line: " . $e->getLine() . " - file: " . $e->getFile();
            //Logging de l erreur
            Log::channel('customlog')->error($message);
            return $this->ReturnResponse(false, $message, [], 500);

        }
    }

        /**
     * this function allows you to create a stock for a space
     * @param integer $stock_id
     * @return JsonResponse
     */
    public function show($stock_id)
    {
        $stock = Stock::where('id',$stock_id)->with(['item','space'])->get()->toArray();

        return $this->ReturnResponse(true, "Les détails sur le stock", $stock, 200);

    }
}
