<?php

namespace App\Http\Controllers;

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


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

        return [
            'size' => sizeof($dataDece),
            'data' => $dataDece
        ];
    }
    /**
     * 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',
            'personne_id' => 'required|exists:personnes,id'
        ]);
        $dataPersonne = Personne::find($req->personne_id);
        $dataDece = Dece::create($champs);
        $dataPersonne->update(['isDead' => true]);

        return $dataDece;
    }

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

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

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

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