<?php

namespace App\Http\Controllers;

use App\Models\Distribution_ouvrage;
use App\Models\Ouvrage_livre;
use Illuminate\Http\Request;


class DistributionOuvrageController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $dataDist = Distribution_ouvrage::all();
        if ($dataDist->isEmpty()) {
            return response()->json(['message' => 'No Distribution data found in Database'], 404);
        }
        return [
            'size' => sizeof($dataDist),
            'data' => $dataDist
        ];
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $req)
    {
        $champs = $req->validate([
            'quantite' => 'required|numeric|gt:0',
            'motif' => 'required|string|max:255',
            'personne_id' => 'required|exists:personnes,id',
            'ouvrage_id' => 'required|exists:ouvrage_livres,id'
        ]);
        $dataOuvrage = Ouvrage_livre::find($req->ouvrage_id);
        // $dataAbandon = Abandon::create($champs);
        if ($dataOuvrage->quantite > $req->quantite) {
            $newQte = $dataOuvrage->quantite - $req->quantite;
            $dataDist = Distribution_ouvrage::create($champs);
            $dataOuvrage->update(['quantite' => $newQte]);
            return $dataDist;
        } else {
            return [
                'message' => "Cet ouvrage n'est plus en stock"
            ];
        }
    }

    /**
     * Display the specified resource.
     */
    public function show($id)
    {
        $dataDist = Distribution_ouvrage::find($id);
        if (!$dataDist) {
            return response()->json(['message' => 'Distribution not found'], 404);
        }

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

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $req,  $id)
    {
        $dataDist = Distribution_ouvrage::find($id);
        if (!$dataDist) {
            return response()->json(['message' => 'Distribution not found'], 404);
        }
        $champs = $req->validate([
            'quantite' => 'required|numeric',
            'motif' => 'required|string|max:255',
            'personne_id' => 'required|exists:personnes,id',
            'ouvrage_id' => 'required|exists:ouvrage_livres,id'
        ]);

        $dataDist->update($champs);
        return $dataDist;
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        $dataDist = Distribution_ouvrage::find($id);
        if (!$dataDist) {
            return response()->json(['message' => 'Distribution not found'], 404);
        }
        $dataDist->delete();

        return ['message' => "Distribution deleted"];
    }
}
