<?php

namespace App\Http\Controllers;

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


class CategorieOuvrageController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $dataCatOuvrage = Categorie_ouvrage::all();
        if ($dataCatOuvrage->isEmpty()) {
            return response()->json(['message' => 'No Categorie Ouvrage data found in Database'], 404);
        }

        return [
            'size' => sizeof($dataCatOuvrage),
            'data' => $dataCatOuvrage
        ];
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $req)
    {
        $champs = $req->validate([
            'designation' => 'required|string|max:255',
            'code' => 'required|string|max:255',
        ]);

        $dataCatOuvrage = Categorie_ouvrage::create($champs);
        return $dataCatOuvrage;
    }

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

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $req,  $id)
    {
        $dataCatOuvrage = Categorie_ouvrage::find($id);
        if (!$dataCatOuvrage) {
            return response()->json(['message' => 'Categorie ouvrage not found'], 404);
        }
        $champs = $req->validate([
            'designation' => 'required|string|max:255',
            'code' => 'required|string|max:255',
        ]);

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

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

        return [
            'message' => "Categorie Ouvrage deleted"
        ];
    }
}