<?php

namespace App\Http\Controllers;

use App\Models\Bapteme;
use App\Models\Personne;
use Illuminate\Http\Request;

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

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

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

        $dataPersonne = Personne::find($req->personne_id);
        $dataBapteme = Bapteme::create($champs);
        $dataPersonne->update(['isBaptized' => true]);

        return $dataBapteme;
    }

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

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

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

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