<?php

namespace App\Http\Controllers;

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

class RapportFideleController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $dataRapport = Rapport_fidele::all();
        if ($dataRapport->isEmpty()) {
            return response()->json(['message' => 'No Rapport fidele 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('sexe', 'M')
            ->count();
        $nbreF = Personne::where('sexe', 'F')
            ->count();

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

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

        return $rapport;
    }

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

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $req,  $id)
    {
        $rapport = Rapport_fidele::find($id);
        if (!$rapport) {
            return response()->json(['message' => 'Rapport fidele not found'], 404);
        }
        $nbreM = Personne::where('sexe', 'M')
            ->count();
        $nbreF = Personne::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_fidele::find($id);
        if (!$rapport) {
            return response()->json(['message' => 'Rapport fidele not found'], 404);
        }
        $rapport->delete();
        return ['message' => 'Rapport fidele deleted'];
    }
}
