<?php

namespace App\Http\Controllers;

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

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

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

    /**
     * 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'
        ]);

        $dataEtat = Etat_civil::create($champs);
        return $dataEtat;
    }

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

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

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

        return [
            'message' => "Etat civil deleted"
        ];
    }
}