<?php

namespace App\Http\Controllers;

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


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

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

        $dataMariage = MariageAll::create($champs);
        return $dataMariage;
    }

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

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

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $req,  $id)
    {
        $dataMariage = MariageAll::find($id);
        if (!$dataMariage) {
            return response()->json(['message' => 'Mariage not found'], 404);
        }

        $champs = $req->validate([
            'lieu' => 'required|string|max:255',
            'observation' => 'required|string|max:255',
            'date' => 'required|date',
            'epoux_id' => 'required|exists:personnes,id',
            'epouse_id' => 'required|exists:personnes,id',
            'type_mariage_id' => 'required|exists:type_mariages,id'
        ]);

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

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