<?php

namespace App\Http\Controllers;

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


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

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $req)
    {
        $champs = $req->validate([
            'titre' => 'required|string|max:255',
            'langue' => 'required|string|max:255',
            'nbre_page' => 'required|numeric',
            'quantite' => 'required|numeric',
            'prix' => 'required|numeric',
            'date_reception' => 'required|date',
            'categorie_id' => 'required|exists:categorie_ouvrages,id'
        ]);
        $dataLivre = Ouvrage_livre::create($champs);
        return $dataLivre;
    }

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

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $req,  $id)
    {
        $dataLivre = Ouvrage_livre::find($id);
        if (!$dataLivre) {
            return response()->json(['message' => 'Livre not found'], 404);
        }
        $champs = $req->validate([
            'titre' => 'required|string|max:255',
            'langue' => 'required|string|max:255',
            'nbre_page' => 'required|string|max:255',
            'quantite' => 'required|string|max:255',
            'prix' => 'required|string|max:255',
            'date_reception' => 'required|date',
            'categorie_id' => 'required|exists:categorie_ouvrages,id'
        ]);
        $dataLivre->update($champs);
        return $dataLivre;
    }

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

        $dataLivre->delete();
        return [
            'message' => "Livre deleted"
        ];
    }
}
