<?php

namespace App\Http\Controllers;

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


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

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

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $req)
    {

        $nbreM = Personne::where('isWidow', true)
            ->where('sexe', 'M')
            ->count();
        $nbreF = Personne::where('isWidow', true)
            ->where('sexe', 'F')
            ->count();

        $nbreTotal = $nbreM + $nbreF;
        $req->merge([
            'nbre_h' =>  $nbreM,
            'nbre_f' =>  $nbreF,
            'nbre_total' =>  $nbreTotal
        ]);

        $rapport = Rapport_veuf::create($req->all());

        return $rapport;
    }

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

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $req,  $id)
    {
        $rapport = Rapport_veuf::find($id);
        if (!$rapport) {
            return response()->json(['message' => 'Rapport Veuf/ve not found'], 404);
        }
        $nbreM = Personne::where('isWidow', true)
            ->where('sexe', 'M')
            ->count();
        $nbreF = Personne::where('isWidow', true)
            ->where('sexe', 'F')
            ->count();

        $nbreTotal = $nbreM + $nbreF;
        $req->merge([
            'nbre_h' =>  $nbreM,
            'nbre_f' =>  $nbreF,
            'nbre_total' =>  $nbreTotal
        ]);

        $rapport->update($req->all());

        return $rapport;
    }

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