<?php

namespace App\Http\Controllers\StockManagement;

use App\DataTables\Stocks\AdjustmentDataTable;
use App\Exceptions\ServerStatus;
use App\Http\Controllers\Controller;
use App\Http\Requests\StockManagement\CreateAdjustmentRequest;
use App\Models\StockManagement\Adjustment;
use App\Models\StockManagement\Stock;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use function Yajra\DataTables\Html\Editor\fields;

class AdjustmentController extends Controller{

    public function dtList(AdjustmentDataTable $dataTable){
        return $dataTable->render("backend.stocks.management.tabs.lots.blocs.list-adjustments");
    }


    public function create(Request $request){
        $data = (array) $request->data[0];
        unset($data['info']);
        $stock = Stock::findOrFail($data['stock_id']);

        DB::beginTransaction();
        try {
            $data['adjuster'] = auth()->user();
            $adjust = $stock->adjust($data);
            $errors = $adjust['errors'];
            $response['message'] = __("Adjustment Successfully");
            $response['success'] = true;
            if ($adjust['success']){
                DB::commit();
                return  response()->json($response,ServerStatus::SUCCESS);
            }


            foreach ($errors['fieldErrors'] as $index => $fieldError) {
                if ($fieldError['name'] == "qty_before"){
                    $errors['fieldErrors'][$index] = ['name' => "info" , "status" =>$fieldError['status'] ];
                }
            }
            unset($errors['messages']);
            return response()->json($errors,ServerStatus::UNPROCESSABLE_ENTITY);

        }catch (\Exception $exception){
            DB::rollBack();
            write_log("stocks/adjustments/create",$exception,"error");
            return response()->json(["message" => general_error($exception)],ServerStatus::APPLICATION_ERROR);
        }
    }
}
